One of the most significant architectural shifts in modern Node.js is the coexistence of two module systems: the legacy CommonJS (CJS) standard created in 2009, and the modern official ECMAScript standard: ES Modules (ESM). Understanding the differences, syntax rules, and interoperability between both systems is essential for every backend developer.
In CommonJS, modules are loaded synchronously via require() and exported by mutating the module.exports or exports object:
// math-cjs.js (CommonJS Export)
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = {
add,
multiply
};
// app-cjs.js (CommonJS Import)
const { add, multiply } = require('./math-cjs');
console.log('Sum:', add(10, 20)); // 30
console.log('Product:', multiply(5, 4)); // 20
To use ES Modules, set "type": "module" in your package.json. You can then use standardized import and export keywords:
// math-esm.js (ESM Named Exports)
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// Default export
export default function calculateTax(amount, rate = 0.18) {
return amount * rate;
}
// app-esm.js (ESM Import)
import calculateTax, { add, multiply } from './math-esm.js';
console.log('Sum:', add(10, 20)); // 30
console.log('Tax on $100:', calculateTax(100)); // 18
Unlike CommonJS where you could omit .js when requiring local files, ES Modules in Node.js require explicit file extensions: import { add } from './math.js'. Omission will trigger an ERR_MODULE_NOT_FOUND exception!
In CommonJS, you could not use await outside of an async function wrapper. ES Modules fully support Top-Level Await, simplifying database connections and asynchronous setup tasks:
// server-esm.js (Top-Level Await)
import http from 'http';
// Asynchronous setup without wrapping in an IIFE
const res = await fetch('https://api.github.com/zen');
const dailyQuote = await res.text();
console.log('GitHub Zen:', dailyQuote);
| Feature | CommonJS (CJS) | ES Modules (ESM) |
|---|---|---|
| Loading Mechanism | Synchronous (blocks execution while loading) | Asynchronous & Static (parsed before execution) |
| Conditional Imports | Allowed: if (cond) require('./a') |
Disallowed for static import (Use dynamic import()) |
| Top-Level Await | No (Throws SyntaxError) | Fully Supported natively |
| Path Resolution | __dirname and __filename globals |
import.meta.url via node:url module |
| Tree Shaking | Poor (V8 cannot statically predict exports) | Optimal (Allows dead-code elimination in bundlers) |
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Learn how __dirname changes in ESM with import.meta.url.
Configure type: module in package.json.
Import fs and fs/promises in ESM.