CommonJS vs ESM
Two module systems in the same language. CommonJS uses require and module.exports and loads synchronously; ES Modules use import and export, are statically analysable, and load asynchronously.
Detailed Explanation
JavaScript had no module system for its first two decades. Node.js shipped in 2009 with CommonJS (CJS) because it needed one immediately. The language standardised ES Modules (ESM) in 2015. Both now run in Node, and the seams between them cause real friction.
Loading model. require() is a synchronous function call. It reads the file from disk, executes it, and returns the exports before the next line runs. That works on a server with a local filesystem and is impossible over a network. ESM resolves its graph in phases — parse, link, evaluate — so imports can be fetched in parallel and ESM works in the browser.
Static versus dynamic. require is a plain function. You can call it inside an if, build the path from a variable, or delete an entry from require.cache. Tools cannot know what a CJS file imports without running it. ESM import must be top-level and literal, which is exactly what enables tree-shaking and reliable static analysis. Both support dynamic import().
Value copy versus live binding. This is the semantic difference people get wrong. require returns the module.exports object as it stood at that moment. Destructuring it takes a snapshot: if the module later reassigns exports.count, your copy does not change. An ESM import is a live read-only binding onto the exporter's variable, so it always reflects the current value.
Strict mode. ESM is always strict. CJS defaults to sloppy mode unless the file says "use strict".
Available globals. CJS files get require, module, exports, __filename and __dirname injected as function-scoped variables. None of these exist in ESM. The replacement is import.meta.url, which holds the module's URL. Convert it with fileURLToPath from node:url, or use import.meta.dirname on Node 20.11+. In ESM, this at the top level is undefined rather than module.exports.
Choosing the mode. Node decides per file. A .mjs file is always ESM and a .cjs file is always CJS. A plain .js file follows the nearest package.json: "type": "module" makes it ESM, and the absence of that field, or "type": "commonjs", makes it CJS.
Interop. ESM can import a CommonJS module; the module.exports object arrives as the default export, and Node's static analysis often detects named exports too, though not always. The reverse does not work synchronously: require() of an ESM file throws ERR_REQUIRE_ESM on older Node versions. Use await import() from CJS instead. Node 22 added limited synchronous require() of ESM that has no top-level await, but relying on it hurts portability.
The costs are practical. Dual-publishing a library in both formats risks the dual package hazard, where a dependency is loaded twice under two systems and instanceof checks across the copies fail. ESM requires file extensions in relative specifiers, which CJS did not. Most test runners and build tools now default to ESM, and it is the right choice for new code; CJS remains everywhere in the existing ecosystem.
Code Examples
counter.cjs — CommonJS. Exports are a plain object, copied on read.
// counter.cjs — CommonJS. Exports are a plain object, copied on read.
let count = 0;
function increment() {
count += 1;
module.exports.count = count; // must reassign the property by hand
}
module.exports = { count, increment };
// main.cjs
const { count, increment } = require("./counter.cjs"); // snapshot taken here
increment();
console.log(count); // => 0 the destructured copy never updates
console.log(require("./counter.cjs").count); // => 1 the object did updatecounter.mjs — ESM. Exports are live bindings.
// counter.mjs — ESM. Exports are live bindings.
export let count = 0;
export function increment() {
count += 1;
}
// main.mjs
import { count, increment } from "./counter.mjs";
increment();
console.log(count); // => 1 the binding is live, not a copy
// __dirname and require do not exist in ESM. Recreate what you need:
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
import { createRequire } from "node:module";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename); // or import.meta.dirname on Node 20.11+
const require = createRequire(import.meta.url); // escape hatch for CJS-only deps
console.log(typeof __dirname); // => stringCommon Gotchas
`require()` of an ES module fails
Node throws `ERR_REQUIRE_ESM` from CommonJS. Use `await import("./mod.mjs")`, or `createRequire` in the other direction.
Destructuring a `require` freezes the value
`const { count } = require(...)` copies the property. Later updates in the exporting module are invisible. ESM bindings stay live.
`__dirname`, `__filename` and `require` are absent in ESM
derive them from `import.meta.url`. Code copied from CJS tutorials fails with a `ReferenceError`.
File extension decides the mode
`.mjs` is ESM, `.cjs` is CJS, and `.js` follows `"type"` in the nearest `package.json`. ESM also requires the extension in relative import paths.