Sub topic 1
Scripts versus modules: what makes a file a module
Prerequisites
This chapter assumes you can:
- Write basic TypeScript types, interfaces, and functions.
- Read JavaScript
importandexportstatements. - Run
tscand edit atsconfig.json. - Use npm and read a
package.json.
You don't need to know about module resolution or declaration files yet. Later chapters cover them.
Two kinds of files
TypeScript sorts every source file into one of two categories before it checks any types.
- A script is a file whose top-level declarations live in the global scope. Every other script in the program can see them.
- A module is a file with its own scope. Its top-level declarations are private unless you export them.
The distinction affects name collisions, how code is emitted, how globals are declared, and which runtime features you can use. Many confusing errors in new projects come from a file being classified differently than you expected.
The rule: a top-level import or export
By default, TypeScript treats a file as a module if it contains at least one top-level import or export statement. Otherwise it is a script.
// counter.ts (a script: no import or export)
const count = 1;// other.ts (also a script)
const count = 2;Both files are compiled in the same global scope, so the compiler reports an error in each:
error TS2451: Cannot redeclare block-scoped variable 'count'.The two const declarations are not independent. Both declare a global named count.
Adding one export to each file changes this.
// counter.ts (a module)
const count = 1;
export function next(): number {
return count + 1;
}// other.ts (a module)
const count = 2;
export const doubled = count * 2;Each count is now local to its file, and the errors disappear. Only next and doubled are visible to other files, and only when imported.
The `export {}` idiom
Sometimes a file has nothing to export but you want it treated as a module. A common case is an entry file that only runs side effects. The idiom is an empty export list.
// setup.ts
const config = { debug: true };
console.log(config.debug);
export {};export {} exports nothing. It still marks the file as a module, so config stays local. In emitted ES module output, the statement stays in the file. In CommonJS output, TypeScript emits a small marker instead.
An empty import "./other.js"; also works, but it adds a runtime dependency. export {} has no such cost.
What else counts as a module marker
An import or export statement is not the only signal. With the default setting moduleDetection: "auto", TypeScript also treats a file as a module in these cases:
- The file uses
import.meta. - The
moduleoption isnode16ornodenext, and the nearestpackage.jsonhas"type": "module". In that case every.tsfile under it is a module, even one with no import or export. A.mtsfile is always a module, and a.ctsfile is always a CommonJS module. - The
jsxoption isreact-jsxorreact-jsxdev, and the file contains JSX.
Top-level await does not make a file a module by itself. If you write it in a file with no imports or exports, TypeScript reports error TS1375 and suggests adding export {}.
// fetch-data.ts
const response = await fetch("https://example.com/data.json");
console.log(response.status);
export {};The export {} line is what makes the top-level await legal. Your module and target settings must also support top-level await. module: "nodenext" with target: "es2022" does.
The `moduleDetection` option
You can change how the compiler classifies files with moduleDetection.
| Value | Behavior |
|---|---|
| `auto` (default) | Uses the signals described above: import or export statements, `import.meta`, `package.json` `"type"` under Node module modes, and JSX under `react-jsx` |
| `legacy` | Only import and export statements make a file a module |
| `force` | Every non-declaration file is a module |
force is useful in projects where every file should be a module. It removes the accidental-script problem, because a file with no exports is still isolated. Declaration files (.d.ts) are exempt. They keep their own rules, which a later chapter covers.
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"moduleDetection": "force",
"strict": true
}
}How TypeScript decides
Why the difference matters
Name collisions
As shown above, two scripts that declare the same top-level name conflict. This also happens with names that already exist in the global scope. A script that declares const name = "x"; conflicts with the name property that the DOM library types add to the global object, if your lib setting includes dom. Making the file a module avoids the clash.
Declaring globals
Scripts can add to the global scope directly. A script containing the following merges a new property into the global Window interface:
// globals.d.ts (a script)
interface Window {
appVersion: string;
}In a module, the same code declares a new local interface named Window. It does not touch the global one. A module must use a declare global block instead:
// globals.ts (a module)
export {};
declare global {
interface Window {
appVersion: string;
}
}This is a frequent source of "my global type is not picked up" bugs. Adding an import to a global .d.ts file silently turns it into a module and breaks the declarations inside it. A later chapter on ambient declarations and augmentation covers this in detail.
Emitted code and runtime behavior
The JavaScript output depends on the classification too.
- A module compiled to ES modules keeps its
importandexportstatements. Runtimes load it with module semantics: strict mode, its own scope, and deferred evaluation. - A module compiled to CommonJS is wrapped in the CommonJS pattern, and TypeScript emits
exportsassignments. - A script is emitted as plain code. In a browser, loading it with a
<script>tag puts its top-levelvarand function declarations on the global object. Under Node.js, it still runs as a CommonJS file with its own function scope.
Strict mode
TypeScript always emits "use strict" for modules when targeting CommonJS, because ES modules are strict by definition. With alwaysStrict or strict enabled, scripts are emitted in strict mode too.
Common mistakes
- A "utility" file with no exports. You write a helper that defines functions but forget to export them. Under
legacydetection it becomes a global script, and calls from other files may work in the editor but fail at runtime because nothing loads it. - Adding an import to a global declaration file. The file becomes a module, and its former globals are no longer global.
- Expecting top-level
awaitto work alone. Addexport {}or a real import or export. - Mixing up
.tsclassification and runtime classification. TypeScript'smoduleDetectionis a compile-time decision. Node.js decides separately, from the file extension andpackage.json"type". Innodenextmode the two agree. In other modes they can disagree, and you will find out at runtime.
Summary
A file is a module when TypeScript sees a top-level import or export, or another signal covered by moduleDetection. Otherwise it is a script and shares the global scope. Use export {} to opt a file into module status, and use moduleDetection: "force" to make it the default. The next chapters build on this: they look at the export and import forms themselves, and at the module formats that Node.js understands.
Exercise
You have two files, a.ts and b.ts, in a project with module set to commonjs and default moduleDetection. Both contain only const total = 0; and nothing else. The compiler reports TS2451 in each. Name two different changes that fix the error without renaming either variable, and say what each one does.
Show answer
First, add export {} (or any real export or import) to each file. This makes each file a module, so total is local to its file. Second, set "moduleDetection": "force" in tsconfig.json. This makes the compiler treat every non-declaration file as a module, so neither total is global. The second change fixes both files at once and also protects future files.
Exercise
A global declaration file globals.d.ts contains interface Window { appVersion: string }. Someone adds import { User } from "./user.js"; at the top, and window.appVersion stops type-checking elsewhere. Why, and how do you fix it while keeping the import?
Show answer
The import turns the file into a module, so interface Window now declares a local interface instead of merging into the global Window. Wrap the declaration in a declare global { ... } block inside the module, so it augments the global scope explicitly.