Difficulty: Beginner
What is the difference between CommonJS and ES Modules in Node.js? How does Node decide which one a file uses, and when would you use each?
CommonJS (CJS) is Node's original module system, using require() and module.exports, and it loads modules synchronously at runtime. ES Modules (ESM) are the JavaScript standard, using import and export, and they are parsed statically before any code runs, which enables top-level await, tree-shaking, and the same syntax as the browser. New projects should default to ESM; CJS remains everywhere in older code and packages.
| Aspect | CommonJS | ES Modules |
|---|---|---|
| Syntax | require, module.exports | import, export |
| Loading | Synchronous, at runtime | Parsed first, then linked and evaluated |
| Exports | A copy of the value at require time | Live bindings to the exporter's variables |
| Conditional loading | require() anywhere | Static import at top; import() for dynamic |
| Top-level await | No | Yes |
__dirname, __filename | Available | Use import.meta.dirname / import.meta.filename (Node 20.11+) |
| File extensions in imports | Optional | Required for relative paths (./utils.js) |
this at top level | module.exports | undefined |
.mjs is always ESM and .cjs is always CommonJS..js, Node looks at the nearest package.json: "type": "module" means ESM, "type": "commonjs" or no field means CJS.type field and the file contains ESM syntax such as import, Node 22.7+ detects that and loads it as ESM (syntax detection), but setting type explicitly is faster and clearer.import pkg from 'cjs-lib' gives you module.exports as the default export, and Node tries to detect named exports.await import(). Since Node 22.12 and 20.19, require() can load ES modules synchronously as long as they do not use top-level await. This removed much of the migration pain for library authors.exports field in package.json with import and require conditions. Watch out for the dual package hazard: if both copies get loaded, you get two instances of the module's state..js extension in an ESM relative import gives ERR_MODULE_NOT_FOUND."module": "nodenext", you write import './utils.js' even though the source file is utils.ts.import data from './data.json' with { type: 'json' }.exports object, while ESM throws a ReferenceError if you touch a binding before it is initialized.Use ESM for new apps and libraries, set "type": "module", and rely on require(esm) only when bridging old code. Keep CJS for existing codebases where a migration has no clear payoff, and for tools or plugins that still expect it.
// math.cjs
let calls = 0;
function add(a, b) { calls++; return a + b; }
module.exports = { add, getCalls: () => calls, calls };
// app.cjs
const math = require('./math.cjs');
console.log(math.add(2, 3)); // 5
console.log(math.calls); // 0 (copied value, not live)
console.log(math.getCalls()); // 1
// Conditional, lazy require (CJS only)
if (process.env.NODE_ENV !== 'production') {
const debug = require('./debug-tools.cjs');
debug.enable();
}
// Same object every time: modules are cached
console.log(require('./math.cjs') === math); // true
require() is synchronous and can be called conditionally. Exports are copied at require time, and the module is cached after the first load, so it behaves like a singleton.
// math.js (package.json has "type": "module")
export let calls = 0;
export function add(a, b) { calls++; return a + b; }
export default function multiply(a, b) { return a * b; }
// app.js
import multiply, { add, calls } from './math.js'; // extension required
import { readFile } from 'node:fs/promises';
import config from './config.json' with { type: 'json' };
console.log(add(2, 3), calls); // 5 1 (live binding)
console.log(multiply(4, 5)); // 20
// Top-level await
const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'));
console.log(pkg.name, config.env);
// Replacements for __dirname / __filename (Node 20.11+)
console.log(import.meta.dirname, import.meta.filename);
// Dynamic import works in both CJS and ESM
const { default: chalk } = await import('chalk');
ESM exports are live bindings, top-level await works, and import.meta replaces __dirname. Relative imports must include the file extension.
{
"name": "@acme/money",
"version": "2.0.0",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"engines": { "node": ">=20.19" }
}
The exports field picks the right entry point based on how the package is loaded. types should come first so TypeScript resolves declarations correctly.
CommonJS, ES Modules, require(esm), package.json type, exports field, Tree-shaking