Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท tsconfig: Language, Modules and Emit Options

TypeScript moduleDetection option

Reference for moduleDetection: how TypeScript decides if a file is a module or a global script, the auto, legacy and force values, and the export {} trick.

A TypeScript file is either a module (its top-level names are private to the file) or a script (its top-level names are global and shared with every other script in the project). moduleDetection controls how the compiler decides.

The traditional rule is that a file is a module if it contains a top-level import or export. With the default auto mode, the compiler also treats a file as a module when the project is in a Node module mode and package.json says "type": "module", or when the file uses JSX in react-jsx mode. This avoids the classic surprise of two scripts declaring the same const name and clashing.

JSON
{ "compilerOptions": { "moduleDetection": "force" } }

Try it

TypeScript Making a file a module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Adding a global from a module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

JSON
{ "compilerOptions": { "moduleDetection": "force" } }
Value Meaning
auto Default. A file is a module if it has import/export, or by the Node "type": "module" and JSX rules described above.
legacy Only a top-level import or export makes a file a module.
force Every non-declaration file is a module, whatever it contains.

Command line: tsc --moduleDetection force.

Usage notes

  • Scripts share one global scope. Two scripts that each declare const name = ... give "Cannot redeclare block-scoped variable". This is the usual reason for the export {}; line you see in small examples.
  • declare global { ... } is allowed only inside a module. In a script you declare globals directly.
  • force is a safe choice for new projects that use ES modules only: no file can accidentally become a global script.
  • Declaration files (.d.ts) are classified by the same top-level import/export rule; a .d.ts with no import/export describes globals, and one with an import/export describes a module.
  • Module-only features that need a module file: import.meta, top-level await, declare global.
  • Scripts are still right for plain browser <script> files without a bundler, and for ambient declaration files meant to add globals.