The Node.js Runtime ExplainedLesson 1.3
Node.js module system: CommonJS vs ES Modules
require vs import, module.exports, named exports, default exports, .mjs vs .cjs, package.json type field, circular dependencies
Two Module Systems
Node.js supports two module formats. CommonJS (CJS) uses require() and module.exports. It is synchronous and has been the default since Node.js began. ES Modules (ESM) uses import/export, runs asynchronously, and is the web standard.
CommonJS
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require('./math');
console.log(add(2, 3)); // 5ES Modules
// math.mjs
export function add(a, b) { return a + b; }
// app.mjs
import { add } from './math.mjs';
console.log(add(2, 3)); // 5Choosing Between Them
Set "type": "module" in package.json to make .js files ESM by default. Use .cjs for any file that must stay CommonJS. New projects should prefer ESM โ it is the long-term standard and enables static analysis and tree-shaking. One hard limit: you cannot use top-level await in CommonJS. ESM allows it natively.
