skip to content

ESM Adoption and Interop

Running ES modules in Node means opting in by extension or the type field, losing __dirname, and crossing the CJS boundary. Asked how to consume CommonJS from ESM and the reverse with require(esm).

on this pageshow

explore

questions

5

In Node.js 24, how does Node decide whether a given .js file runs as an ES module or as CommonJS?

level: juniorimportance: must knowfreq 64%

answer

  1. extension before package.json
  2. .mjs and .cjs never change
  3. nearest package.json type field
  4. no marker: CommonJS first
  5. reparse when module syntax appears

basics

~20 s

An .mjs file is always an ES module and a .cjs file always CommonJS. A .js file follows the nearest package.json "type" field; without one, Node 24 tries CommonJS and reparses as ESM if it finds module syntax.

solid answer

~40 s

Node looks for an explicit marker first. The extension wins outright: `.mjs` is always an ES module and `.cjs` is always CommonJS, whatever any `package.json` says. For a `.js` file Node reads the nearest parent `package.json`: `"type": "module"` makes it ESM, `"type": "commonjs"` makes it CommonJS. Code passed to `--eval` or piped on stdin follows `--input-type`. With no marker at all the file is ambiguous, and since Node 22.7 (so in Node 24) syntax detection tries it as CommonJS and, if the parser meets ES module syntax such as `import`, `export`, `import.meta` or top-level `await`, reparses it as an ES module. That fallback costs a second parse, which is why the docs ask every package to declare `"type"`, even an all-CommonJS one.

code

console · 4 lines
console
$ node --input-type=module -e "console.log(typeof require)"
undefined
$ node --input-type=commonjs -e "console.log(typeof require)"
function

go deeper

for a junior

Recall the order: .mjs and .cjs decide outright, then the nearest package.json "type" field decides .js files, and only unmarked files fall back to detection.

for a middle

Explain that the nearest package.json wins, including a nested one without "type", and how syntax detection tries CommonJS first and reparses on ES module syntax.

for a senior

Show you would declare "type" everywhere, including emitted build folders, and read a MODULE_TYPELESS_PACKAGE_JSON warning as a missing declaration with a parse cost.

for a principal

Frame explicit markers as a team rule: format by guess is a startup cost and a portability risk, so linting or CI should require "type" in every package the team owns.

Node.js has two module systems. **CommonJS** is the original one: files call `require()` and assign `module.exports`. **ES modules (ESM)** are the standard format: files use `import` and `export`. The two are loaded by different loaders with different rules, so before Node can run a file it has to decide which system the file belongs to. In Node 24 that decision follows a fixed order of precedence. ## Explicit markers come first An explicit marker is anything that states the format outright. Node honours these before it looks at the code: | Marker | Result | |---|---| | `.mjs` extension | Always an ES module | | `.cjs` extension | Always CommonJS | | `.js` under a `package.json` with `"type": "module"` | ES module | | `.js` under a `package.json` with `"type": "commonjs"` | CommonJS | | `--eval` or stdin with `--input-type=module` | ES module | | `--eval` or stdin with `--input-type=commonjs` | CommonJS | The extension beats the `package.json`. That is what makes mixed packages possible: - inside a `"type": "module"` package, a file named `legacy.cjs` stays CommonJS; - inside a `"type": "commonjs"` package (or one with no `"type"`), a file named `tool.mjs` is an ES module. ## The nearest package.json decides for .js files For a `.js` file Node walks up from the file's directory and stops at the **nearest** `package.json`. Three details follow from "nearest": - A subfolder with no `package.json` of its own inherits the decision from the one above it. - A subfolder that *does* hold a `package.json` is decided by that file alone. If it lacks `"type"`, its `.js` files are ambiguous even when the root says `"type": "module"`. Builds that emit a small `package.json` into an output folder should write the `"type"` they mean. - An installed dependency has its own `package.json`, so your app's `"type"` never changes how a dependency in `node_modules` is loaded. The field applies to entry points (`node server.js`) and equally to every file reached through `import` statements or `import()` expressions. ## Syntax detection for ambiguous files A file is **ambiguous** when it has a `.js` extension (or none) and its controlling `package.json` is missing or has no `"type"` field. Since Node 22.7 syntax detection is on by default, so in Node 24 an ambiguous file is tried as CommonJS first and reparsed as an ES module only if the parse fails on syntax that is legal only in ESM: 1. `import` statements (but not `import()` expressions, which CommonJS allows); 2. `export` statements; 3. `import.meta` references; 4. `await` at the top level of the file; 5. lexical redeclarations of the CommonJS wrapper variables, such as `const require = ...`. Detection costs a second parse of the file. For a typeless `package.json` outside `node_modules`, Node's ES module loader can also emit a `MODULE_TYPELESS_PACKAGE_JSON` warning asking you to add `"type": "module"`. The docs recommend declaring `"type"` in every package, including all-CommonJS ones, so the format never depends on a guess. `--no-experimental-detect-module` turns detection off; the ambiguous file then runs as CommonJS, and ESM syntax inside it is a `SyntaxError`, which is what Node did before 22.7. ## What the decision changes at load time Choosing the format chooses everything the file can rely on: - **As CommonJS**, the file runs inside the module wrapper and gets `require`, `module`, `exports`, `__filename` and `__dirname`. - **As an ES module**, none of those exist; the file uses `import`, `export` and `import.meta`, runs in strict mode, and its relative import specifiers must carry a full file extension (the resolution rules are a separate subject). - Flipping a package to `"type": "module"` therefore converts every `.js` file in it at once. Any file that still uses `require` or `module.exports` has to be renamed to `.cjs` or rewritten. ## Practical rules 1. Declare `"type"` in every `package.json` you own. 2. Use `.cjs` or `.mjs` only for the files that differ from the package default. 3. When a build writes its own `package.json` into an output folder, write `"type"` into it too. 4. Treat a `MODULE_TYPELESS_PACKAGE_JSON` warning as a missing declaration, not as noise. ## Checking what Node decided When a file behaves unexpectedly, confirm the format before debugging anything else. Inside the file, `typeof require` is `'function'` in CommonJS and `'undefined'` in an ES module, and in a file that is explicitly CommonJS (a `.cjs` file, say) `import.meta` is a `SyntaxError`. From the outside, read the file's extension, then the nearest `package.json` above it, in that order; if neither marks the format, the answer depends on the file's syntax. A useful habit in continuous integration is to run the test suite once with `--no-experimental-detect-module`: any file that only works because detection guessed ESM then fails loudly, which points straight at the `package.json` that needs a `"type"`.

  • A dist/ folder holds its own package.json with only a name, while the root package.json says "type": "module". How are the .js files in dist/ loaded?
    The nearest `package.json` decides, and the one in `dist/` has no `"type"`, so those files are ambiguous rather than inheriting `module` from the root. Node 24 runs each as CommonJS and reparses it as an ES module only if it meets ES module syntax. The fix is to write the intended `"type"` into the emitted `package.json`.
  • Does "type": "module" in your application's package.json change how a dependency in node_modules is loaded?
    No. Each `.js` file is governed by its own nearest `package.json`, and an installed package ships its own. A dependency that declares nothing is ambiguous to Node, so it runs as CommonJS unless its code contains ES module syntax; your app's `"type"` is never consulted for it.

  • Setting "type": "module" in the app also turns its dependencies into ES modules.
  • A .cjs file inside a "type": "module" package is loaded as an ES module.
  • Node 24 still needs the --experimental-modules flag to run ES modules.
  • A .js file without a "type" field and with import statements always throws a SyntaxError in Node 24.
  • One dynamic import() call is enough to make Node treat a file as an ES module.

Assumes Node.js 24; syntax detection of ambiguous .js files has been on by default since v22.7.0, and earlier releases ran such files as CommonJS and threw on import statements.

open as a page

Moving a Node.js 24 file from CommonJS to ESM, which CommonJS module-scope bindings disappear, and what does Node offer in place of each?

level: middleimportance: must knowfreq 58%

basics

~10 s

In an ES module, require, module, exports, __filename and __dirname do not exist. Node 24 replaces them with import and export, import.meta.filename and import.meta.dirname, import.meta.resolve(), and module.createRequire(import.meta.url) when a real require is still needed.

open as a page

When a Node.js 24 ES module imports a CommonJS file, what does the resulting namespace contain, and when are its named exports fixed?

level: middleimportance: should knowfreq 42%

basics

~20 s

Node builds a namespace whose default export is the CommonJS module.exports value, plus a 'module.exports' key with the same value. Extra named exports come from static analysis of the source and are copied once at import, never updated live.

open as a page

In a CommonJS Node.js 24 service, what does require() return for an ESM-only dependency, and when does it throw ERR_REQUIRE_ASYNC_MODULE instead?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Node 24's require() loads a synchronous ES module and returns its module namespace object, with any default export under .default. If the module or anything it imports uses top-level await, require() throws ERR_REQUIRE_ASYNC_MODULE and import() must be used instead.

open as a page

You lead a large CommonJS Node.js 24 service that now depends on one ESM-only and one CommonJS-only package; how do you decide whether, and how, to move it to ESM?

level: principalimportance: should knowfreq 30%

basics

~20 s

In Node 24, require() loads synchronous ES modules, so an ESM-only dependency without top-level await no longer forces a migration. Decide on cost: tests, mocks and require-patching tools, against what ESM buys, such as top-level await.

open as a page