Node supports two module systems: CommonJS (CJS) — the original, using require/module.exports — and ES Modules (ESM) — the standard, using import/. They differ in syntax, loading behavior, and interop.
Node supports two module systems: CommonJS (CJS) — the original, using require/module.exports — and ES Modules (ESM) — the standard, using import/. They differ in syntax, loading behavior, and interop.
export// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require("./math"); // synchronous, runtime
// math.mjs (or .js with "type": "module")
export function add(a, b) { return a + b; }
export default something;
// app.mjs
import { add } from "./math.mjs"; // static, hoisted
CommonJS ES Modules
Syntax require/module.exports import/export
Loading synchronous, runtime static, hoisted
Top-level await no yes
Tree-shaking hard yes (statically analyzable)
File extension .cjs / .js (default) .mjs / .js with "type":"module"
__dirname/__filename available not available (use import.meta.url)
// package.json
{ "type": "module" } // now .js files are treated as ESM
Or use the .mjs extension explicitly. Without this, Node defaults .js to CommonJS.
// ESM can import CommonJS:
import pkg from "some-cjs-lib"; // works (default import)
// CommonJS CANNOT require() a pure-ESM package (it's async):
const esm = require("esm-only-pkg"); // ❌ ERR_REQUIRE_ESM
// must use dynamic import: const esm = await import("esm-only-pkg");
The rough edge: CJS can't require() ESM-only packages — a common migration pain. Also note ESM lacks __dirname (use import.meta.url).
Knowing both systems is essential for real Node work: ESM is the future (standard, tree-shakeable, top-level await, browser-aligned) and the right choice for new projects, but a vast amount of the npm ecosystem and existing code is CommonJS.
Understanding the syntax differences, how to enable ESM ("type": "module"), and the interop limitations (especially CJS-can't-require-ESM) prevents the frequent confusion and errors that arise when mixing them.