Sub topic 4
CommonJS versus ES modules in Node.js
Node.js runs two module systems side by side. CommonJS (CJS) is the original one, built on require and module.exports. ES modules (ESM) are the language standard, built on import and export. TypeScript has to know which system each file uses, because that decides what it emits and which imports it accepts. This chapter covers how Node picks the system for a file, how the two differ at runtime, and how TypeScript reflects those rules.
This chapter assumes you can write import and export statements, edit tsconfig.json, and read a package.json. Later chapters cover the module option, resolution, and interop settings in detail. Here we build the runtime model they rely on.
How Node decides which format a file uses
Node does not guess from the syntax by default. It uses the file extension, and for .js files it uses the nearest package.json.
| File extension | Format |
|---|---|
| `.mjs` | ES module, always |
| `.cjs` | CommonJS, always |
| `.js` | Set by the `"type"` field of the nearest `package.json` |
The "type" field accepts "module" or "commonjs". If the field is missing, .js files are CommonJS. "Nearest" means Node walks up from the file's directory until it finds a package.json.
The same code in both systems
A CommonJS module assigns to module.exports, and a consumer calls require.
// math.cjs
function add(a, b) {
return a + b;
}
module.exports = { add };// main.cjs
const { add } = require("./math.cjs");
console.log(add(1, 2)); // 3The ES module version uses export and import.
// math.mjs
export function add(a, b) {
return a + b;
}// main.mjs
import { add } from "./math.mjs";
console.log(add(1, 2)); // 3The visible syntax is only part of the difference. The two systems also load and link code differently.
Differences that affect your code
Loading: synchronous versus asynchronous
require is an ordinary function call. It reads the file, runs it, and returns module.exports before the next line executes. It can appear anywhere, including inside an if or a function body, and the path can be computed.
import declarations are static. Node parses the whole import graph before running any code, then evaluates modules in dependency order. Because loading is asynchronous, ESM supports top-level await. CommonJS does not.
// config.mjs
const response = await fetch("https://example.com/config.json");
export const config = await response.json();Any module that imports config.mjs waits until that promise settles. For loading a module conditionally, ESM provides import(). It returns a promise and works in both formats.
Live bindings versus copied values
An ESM import is a read-only view of the exporting module's variable. If the exporter changes the variable, importers see the new value. CommonJS copies the value at the moment of destructuring.
// counter.mjs
export let count = 0;
export function increment() {
count++;
}// main.mjs
import { count, increment } from "./counter.mjs";
console.log(count); // 0
increment();
console.log(count); // 1The CommonJS equivalent behaves differently.
// counter.cjs
let count = 0;
function increment() {
count++;
}
module.exports = { count, increment };// main.cjs
const { count, increment } = require("./counter.cjs");
console.log(count); // 0
increment();
console.log(count); // still 0, because count was copiedFile extensions and directory imports
ESM in Node requires the full file name in relative imports. import "./math" fails, and import "./utils" does not resolve to ./utils/index.js. CommonJS tries several extensions and directory index files for you.
This is why TypeScript projects targeting Node ESM write .js in the import path even though the source file is .ts. TypeScript does not rewrite paths, so you write the name of the file that will exist after compilation.
Module-scope variables that do not exist in ESM
CommonJS wraps each file in a function that supplies require, module, exports, __filename, and __dirname. ES modules receive none of these. Using them throws a ReferenceError at runtime, for example require is not defined in ES module scope. ESM gets its location from import.meta.url.
// paths.mjs
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
console.log(__dirname);Node 20.11 and later also provide import.meta.dirname and import.meta.filename.
Strict mode and `this`
ES modules are always in strict mode. At the top level of an ES module, this is undefined. At the top level of a CommonJS module, this is module.exports.
Crossing the boundary
Mixing the formats is where most errors appear.
- ESM importing CJS. This always works. The
module.exportsvalue becomes the default import. Node also tries to detect named exports by scanning the CJS source, but this succeeds only for simple patterns. If a named import fails, use the default import and destructure it. - CJS importing ESM with
require. This failed for years withERR_REQUIRE_ESM. Recent Node versions (22.12 and later) allow it when the ES module graph has no top-levelawait. On older versions, useawait import()instead. - CJS importing ESM with
import(). This works everywhere becauseimport()returns a promise.
// loader.cjs
async function main() {
const { add } = await import("./math.mjs");
console.log(add(1, 2));
}
main();// uses-cjs.mjs
import counter from "./counter.cjs";
counter.increment();The esModuleInterop setting and default-import behavior get their own chapter. For now, remember that Node's rule is simple: the whole module.exports object becomes the default export.
What TypeScript does with this
With "module": "nodenext" (or node16), TypeScript applies Node's rules to each file individually. It decides the format using the same extension and package.json logic as Node, then checks and emits the file as that format.
TypeScript adds two extensions that mirror .mjs and .cjs.
| Source file | Format | Emitted file | Declaration file |
|---|---|---|---|
| `.ts` | From `package.json` `"type"` | `.js` | `.d.ts` |
| `.mts` | ES module | `.mjs` | `.d.mts` |
| `.cts` | CommonJS | `.cjs` | `.d.cts` |
A minimal setup for an ESM project looks like this.
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"outDir": "dist"
},
"include": ["src"]
}Add "type": "module" to package.json, and every .ts file in the project is emitted as ESM. TypeScript keeps import and export as written. Without that field, the same .ts files compile to CommonJS: TypeScript rewrites import declarations into require calls and export into assignments on exports.
A file that only uses import and export can be either format. The format is decided by the configuration, not by the syntax. Two consequences follow:
- The same source can behave differently when you move it to a package with a different
"type"value. - In a CommonJS-format file, TypeScript compiles a static
importtorequire. Importing an ES-module-only package from such a file can therefore fail. In older TypeScript versions this reports error TS1479. The fix is to switch the file to ESM or useawait import("pkg").
TypeScript also checks relative paths. In an ESM-format file under nodenext, import { add } from "./math" is an error, and you must write "./math.js".
A quick diagnostic checklist
When an import fails at runtime or compile time, check these in order:
- Which format does the importing file have, based on its extension and the nearest
package.json? - Which format does the imported file or package have?
- Does the relative path include the full file name with its
.js,.mjs, or.cjsextension? - Are you using
require,__dirname, ormodule.exportsinside an ESM file? - Is a named import failing against a CJS module? Switch to a default import.
Summary
Node chooses CJS or ESM per file from the extension or from the "type" field. ESM loads asynchronously, exports live bindings, requires full file names, and has no require or __dirname. CJS loads synchronously and copies values. TypeScript under nodenext follows the same per-file rules, so a TypeScript file's behavior depends on its configuration as well as its source.
Exercise
A project has no "type" field in package.json. It contains src/app.ts, src/util.mts, and src/legacy.cts, compiled with "module": "nodenext". What format does each file have, and what extension does each emit?
Show answer
src/app.ts is CommonJS because the "type" field is missing, and it emits app.js. src/util.mts is always an ES module and emits util.mjs. src/legacy.cts is always CommonJS and emits legacy.cjs.
Exercise
A file named server.mjs contains const dir = __dirname;. TypeScript reports no error, but running the file fails. Why, and how do you fix it?
Show answer
ES modules do not receive the CommonJS wrapper variables, so _dirname is not defined at runtime. TypeScript did not complain because @types/node declares _dirname as a global. Fix it by computing the directory from import.meta.url with fileURLToPath and path.dirname, or by using import.meta.dirname on Node 20.11 and later.
Exercise
A module exports let count = 0 and an increment() function that does count++. Under which system does an importer see the updated value after calling increment(): ESM with import { count }, or CommonJS with const { count } = require(...)? Explain why.
Show answer
ESM. Imports are live bindings, so the importer reads the exporting module's current variable. Destructuring a require() result copies the value at that moment, so the CommonJS importer keeps seeing 0.