Sub topic 2
ESM and CommonJS: how a file's format is decided
This chapter assumes you can write TypeScript with import and export, run tsc with a tsconfig.json, and read a package.json. It also assumes you know that Node.js runs two module systems. Here you will learn the rules that decide which system each file belongs to, because nodenext resolution depends on that answer.
Two formats, one syntax
ES modules (ESM) and CommonJS (CJS) are the two module formats Node.js runs. They differ at runtime:
| Feature | ESM | CommonJS |
|---|---|---|
| Import syntax | `import x from "y"` | `const x = require("y")` |
| Export syntax | `export const x = 1` | `module.exports = ...` or `exports.x = ...` |
| Loading | Asynchronous, statically analyzed | Synchronous, evaluated when called |
| Top-level `await` | Allowed | Not allowed |
| `__dirname`, `__filename`, `require` | Not defined | Defined |
| `import.meta` | Available | Not available |
| Relative import specifiers | Need the full file extension | Extension optional, directory index files work |
In TypeScript you write import and export in both cases. The source syntax does not tell you what the compiler will emit. In a CJS file, tsc turns your import statements into require() calls. In an ESM file, it keeps them as import. The compiler therefore has to decide the format of each file before it can resolve or emit anything.
Format is a property of each file
Under module: "nodenext", TypeScript decides the format of every file separately. One project can contain both ESM and CJS files, and tsc checks each according to its own format.
The rules apply in this order:
- If the extension is
.mts,.mjs, or.d.mts, the file is ESM. - If the extension is
.cts,.cjs, or.d.cts, the file is CommonJS. - If the extension is
.ts,.tsx,.js,.jsx, or.d.ts, TypeScript finds the nearestpackage.jsonand reads its"type"field."module"means ESM."commonjs"means CJS. - If the nearest
package.jsonhas no"type"field, or nopackage.jsonexists, the file is CommonJS.
The extension always wins. A .cts file inside a "type": "module" package is still CommonJS.
The nearest package.json
"Nearest" means TypeScript starts in the file's own directory and walks upward until it finds a package.json. It reads that one file and stops. It does not keep searching for a "type" field in parent packages.
Consider this layout:
my-app/
package.json { "type": "module" }
src/
main.ts ESM (nearest package.json: my-app, type module)
util.cts CJS (extension wins)
legacy/
package.json { }
old.ts CJS (nearest package.json has no type)src/legacy/package.json has no "type" field. TypeScript stops at it, so old.ts is CommonJS even though the project root says "module". A small package.json placed in a subfolder to mark a CJS island is a legitimate technique. An accidental one is a common source of confusing errors.
A minimal package that sets ESM as the default looks like this:
{
"name": "my-app",
"version": "1.0.0",
"type": "module"
}Declaration files follow the same rules
A .d.ts file also gets its format from the nearest package.json. Use .d.mts for ESM-only declarations and .d.cts for CommonJS declarations. The pairing between source and declaration extensions is:
| Source | Emitted JavaScript | Declaration file |
|---|---|---|
| `.ts` | `.js` | `.d.ts` |
| `.mts` | `.mjs` | `.d.mts` |
| `.cts` | `.cjs` | `.d.cts` |
This pairing matters when you publish a library that ships both formats. It comes up again in the chapters on exports maps and publishing.
What the format changes in your code
The format determines which features compile, and the compiler reports errors for the wrong ones. In an ESM file:
// src/main.ts in a package with "type": "module"
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
// __dirname does not exist in ESM, so derive it from import.meta.url.
const here = fileURLToPath(new URL(".", import.meta.url));
const config = await Promise.resolve({ name: "demo" }); // top-level await is allowed
console.log(here, config.name, typeof readFileSync);The same code in a CommonJS file fails in two places. import.meta is an error, because the compiler reports that it is not allowed in files that compile to CommonJS. Top-level await is also an error. In a CJS file you would use __dirname directly and wrap asynchronous work in a function.
CommonJS files have two TypeScript-specific forms. Use export = to set module.exports to a single value. Use import x = require("y") to import that kind of module explicitly:
// src/helpers.cts
import path = require("node:path");
function join(...parts: string[]): string {
return path.join(...parts);
}
export = join;Neither form is allowed in an ESM file under nodenext. TypeScript reports an error there, because the output would not run.
The emitted code follows the format
Under nodenext, tsc writes JavaScript that matches each file's format. Given a file src/value.cts with export const answer = 42;, the output is CommonJS. Given src/value.mts with the same line, the output keeps export. You do not choose the output shape in tsconfig.json, because the file's format already decides it. This is the main difference from older configurations, where "module": "commonjs" made every file CommonJS.
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist"
}
}With this configuration, the extension rules above are the only things that choose between ESM and CJS output.
Files with no imports or exports
By default, TypeScript treats a file with no import or export as a script, which means its top-level declarations are global. Under module: "nodenext", the moduleDetection default of "auto" also forces a file in an ESM package to be treated as a module, even when it has no import or export. For a CJS file, the usual rule applies. If you see "cannot redeclare block-scoped variable" errors across unrelated files, adding export {}; to each file turns it into a module. Setting "moduleDetection": "force" does the same for every file.
Common errors
These are the mistakes this chapter's rules explain:
- A file is ESM when you expected CJS. The nearest
package.jsonhas"type": "module". Check it, or rename the file to.cts. - A file is CJS when you expected ESM. The
package.jsonhas no"type"field. A missing"type"means CommonJS, not "undecided". - A
package.jsonin a subfolder changes the format of a subtree. Look for straypackage.jsonfiles, such as ones generated by tools or copied from templates. __dirname is not definedat runtime means an ESM file used a CJS global.import.metais not allowed at compile time means the file was classified as CommonJS.
Does `module` or `moduleResolution` decide the format?
Neither option decides it alone. Under module: "nodenext", the per-file rules above apply, and moduleResolution is set to nodenext automatically. Under module: "preserve" with moduleResolution: "bundler", TypeScript does not emit require() calls or rewrite your imports at all. It leaves your import and export statements as written and checks them under bundler rules. The next chapter covers how the two options relate. For now, remember that per-file format detection is a feature of the Node-style modes.
Exercise
A project's root package.json has "type": "module". It contains src/server.ts, src/tools/build.cts, and src/vendor/package.json (containing { "name": "vendor" }) next to src/vendor/parse.ts. Under module: "nodenext", what format is each of the three source files?
Show answer
src/server.ts is ESM, because its nearest package.json is the root one and says "module". src/tools/build.cts is CommonJS, because the .cts extension overrides the "type" field. src/vendor/parse.ts is CommonJS, because its nearest package.json is src/vendor/package.json, which has no "type" field, and a missing "type" means CommonJS.
Exercise
Your ESM file src/paths.ts fails to compile with an error about __dirname. Write the replacement for const dir = __dirname;, and say what the file needs to import.
Show answer
Use const dir = fileURLToPath(new URL(".", import.meta.url)); with import { fileURLToPath } from "node:url";. In ESM there is no __dirname, so you build the directory from import.meta.url.
Exercise
You add "type": "module" to a package and keep "module": "nodenext". Name two things that can change for existing .ts files with no extension rename.
Show answer
First, the files become ESM, so tsc emits import and export instead of require and exports, and CJS-only features such as export = or __dirname become errors. Second, relative imports in those files must now include a file extension such as ./greet.js.