Sub topic 4
ESM and CommonJS: what the file extension and type field mean
This chapter assumes you can write TypeScript with import and export, and that you have run tsc with a tsconfig.json. It also assumes you know what a package.json is. You don't need to know how Node decides whether a file is ESM or CommonJS. That is the subject here.
The decision matters for library authors because the format of each emitted file determines three things:
- how Node loads it
- how TypeScript reads its declaration file
- which consumers can use your package
Two module systems in one runtime
JavaScript has two module systems, and Node.js supports both.
- CommonJS (CJS) is the original Node system. It uses
require()andmodule.exports. Loading is synchronous, andrequireis an ordinary function that can be called anywhere, with any string. - ECMAScript modules (ESM) are the language standard. They use
importandexport. Imports are static and analyzed before the code runs. Loading is asynchronous, and the file can use top-levelawait.
The two systems also differ in details that you will hit while writing a library:
| Feature | CommonJS | ESM |
|---|---|---|
| Import syntax | `require("x")` | `import x from "x"` |
| Export syntax | `module.exports = ...` | `export ...` |
| Current file path | `__dirname`, `__filename` | `import.meta.url` |
| Top-level `await` | Not available | Available |
| Relative import extension | Optional (`./util`) | Required (`./util.js`) |
| Strict mode | Opt in | Always on |
Because ESM requires the file extension in relative imports, the library in this tutorial writes import { slugify } from "./slugify.js" even though the source file is slugify.ts. TypeScript does not rewrite import paths. It checks that ./slugify.js maps to a source file, and it emits the path unchanged. The .js is the name of the file that will exist after the build.
How Node decides which format a file uses
Node does not guess from the syntax inside a file. It decides from the file's extension and, for .js files, from the nearest package.json.
- A
.mjsfile is always ESM. - A
.cjsfile is always CommonJS. - A
.jsfile takes its format from the"type"field of the closestpackage.json, found by walking up from the file's folder."type": "module"means ESM."type": "commonjs"means CommonJS. - If
"type"is missing,.jsfiles are CommonJS.
The "type" field applies to the whole package folder, not only to your library code. If you set "type": "module", a root-level eslint.config.js or jest.config.js is now ESM too. A config file that uses module.exports will fail until you rename it to .cjs.
The field has a second effect that surprises people. "type" governs the files you ship, so it also governs what tsc produces. The slugify library from this tutorial sets "type": "module", so its emitted dist/index.js is ESM.
What TypeScript does with the same rules
With "module": "NodeNext" in tsconfig.json, TypeScript applies Node's rules to your source files. It looks at the same package.json to decide whether a .ts file is ESM or CommonJS. It then type-checks and emits it accordingly. TypeScript also has extensions that match the Node ones:
| Source file | Emitted JavaScript | Emitted declaration | Format |
|---|---|---|---|
| `a.mts` | `a.mjs` | `a.d.mts` | Always ESM |
| `a.cts` | `a.cjs` | `a.d.cts` | Always CommonJS |
| `a.ts` | `a.js` | `a.d.ts` | Set by the `type` field |
This table explains the file names you saw in the dual-package example earlier in the plan. The CommonJS entry is index.cjs, and its types are index.d.cts. A .d.ts file in a "type": "module" package describes ESM. A .d.cts file describes CommonJS. Pairing the wrong declaration file with a JavaScript file is a frequent source of type errors for consumers, and a later chapter covers it.
Under NodeNext, the format of the file also changes how import statements are emitted. In an ESM file, import stays as import. In a CommonJS file, TypeScript compiles import { x } from "y" into a require call. A dynamic import("y") is kept as it is in both, because CommonJS code can load ESM only through a dynamic import.
Here is an ESM-only library file that needs the current file's folder. It uses import.meta.url, which exists only in ESM:
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const here = dirname(fileURLToPath(import.meta.url));
export const dataFile: string = join(here, "data.json");This compiles under NodeNext when package.json says "type": "module" and @types/node is installed. If you remove the type field, TypeScript reports an error on import.meta, because the file is now treated as CommonJS. That error is useful. It shows that the type field changes what the compiler accepts, not only how files run.
Crossing between the two formats
A package rarely lives in isolation, so you need to know what happens when one format loads the other.
- ESM importing CommonJS works. The default import is the whole
module.exportsvalue. Named imports work only when Node can detect the export names by static analysis of the file, which fails for some patterns. Use the default import when in doubt. - CommonJS requiring ESM depends on the Node version. Older versions throw an error. Node 22.12 and later can
require()an ESM file, provided the file and its imports do not use top-levelawait. Many users are still on older versions. - Either format using dynamic
import()works. It returns a promise, so it can't replacerequirein code that needs a synchronous result.
This is what a CommonJS consumer sees when it requires an ESM-only package on an older Node:
Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/@acme/slugify/dist/index.js not supported.That error is the main reason some libraries ship both formats.
Choosing a format for your library
Use these criteria to decide.
- ESM-only. This is the simplest option. You get one build, one set of declaration files, and no risk of mismatched formats. It suits new libraries whose users are on current Node or use a bundler.
- Dual ESM and CommonJS. This reaches every consumer, but you maintain two builds and two sets of types. You also risk the dual package hazard: a program can load both copies of your library, so classes and singletons exist twice and
instanceofchecks between them fail. - CommonJS-only. This is rarely a good choice for a new library. ESM consumers can still import it, but you lose static named exports and top-level
await.
A practical default is to start ESM-only, as in the tutorial's first package.json. Add a CommonJS build only when a real consumer needs it.
Common mistakes
- Forgetting the
.jsextension in relative imports. Node fails at runtime withERR_MODULE_NOT_FOUND, even thoughtscmay have compiled without complaint under older settings.NodeNextreports the error at compile time. - Setting
"type": "module"without updating config files. Tools that load.jsconfig withrequirebreak. Rename them to.cjsor convert them. - Writing
.tsin an import path. Use.js. The import names the output file. - Using
__dirnamein an ESM file. It is not defined. Useimport.meta.urlas shown above. - Assuming the
typefield controls.d.tsfiles only. It controls the interpretation of every.jsand.d.tsfile in its scope.
Exercise
A package has "type": "module" in its package.json. It contains the files dist/index.js, dist/legacy.cjs and dist/types.d.ts. State the module format of each file, and explain why a CommonJS consumer on Node 20 gets ERRREQUIREESM when it calls require("@acme/slugify") with only these files.
Show answer
dist/index.js is ESM, because .js takes its format from "type": "module". dist/legacy.cjs is CommonJS, because the .cjs extension always overrides the type field. dist/types.d.ts is read as the declarations for an ESM file, because it is a .d.ts in a "type": "module" scope. A CommonJS consumer calling require() reaches dist/index.js, which is ESM, and Node 20 cannot require() an ES module. It throws ERRREQUIREESM. To fix this, the package must either ship a CommonJS build (such as a .cjs entry with a .d.cts declaration file) or tell consumers to use import().
Exercise
You write a library file named config.ts in a package without a "type" field and use import.meta.url in it. With "module": "NodeNext", what happens, and what are two ways to fix it?
Show answer
TypeScript treats the file as CommonJS, because a missing "type" field means commonjs, so it reports an error on import.meta. The first fix is to add "type": "module" to package.json so the file becomes ESM. The second is to rename the file to config.mts so it is always ESM, which emits config.mjs.