The Module System: CommonJS & ESM
12 min read
The Module System
Node.js has two module systems: CommonJS (the original, uses require and module.exports) and ESM — ECMAScript Modules (the modern standard, uses import and export). Understanding both is essential because many packages still ship CommonJS.
CommonJS
js
// math.js — CommonJS export
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };js
// main.js — CommonJS import
const { add, subtract } = require("./math");
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2ESM (ECMAScript Modules)
To use ESM in Node.js, either rename files to .mjs, or add "type": "module" to your package.json. ESM supports static analysis, tree-shaking, and top-level await.
js
// math.mjs — ESM export
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export default { add, subtract };js
// main.mjs — ESM import
import { add, subtract } from "./math.mjs";
console.log(add(10, 4)); // 14
console.log(subtract(10, 4)); // 6You cannot mix require and import in the same file. In ESM files, __dirname is not defined — use import.meta.url and path.dirname instead.
Ready to test yourself?
Practice Node.js— quiz & coding exercises