Node ondersteunt twee modulsystemen: CommonJS (CJS) — het origineel, met require/module.exports — en ES Modules (ESM) — de standaard, met import/. Ze verschillen in syntaxis, laadgedrag en interop.
Node ondersteunt twee modulsystemen: CommonJS (CJS) — het origineel, met require/module.exports — en ES Modules (ESM) — de standaard, met import/. Ze verschillen in syntaxis, laadgedrag en 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
Of gebruik de .mjs-extensie expliciet. Zonder dit stelt Node .js standaard in op 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");
De lastige kant: CJS kan ESM-only packages niet require() — een veel voorkomend migratieprobleem. Merk ook op dat ESM geen __dirname heeft (gebruik import.meta.url).
Beiden systemen kennen is essentieel voor echt Node-werk: ESM is de toekomst (standaard, tree-shakeable, top-level await, browser-aligned) en de juiste keuze voor nieuwe projecten, maar een groot deel van het npm-ecosysteem en bestaande code is CommonJS.
Inzicht in de syntaxisverschillen, hoe ESM in te schakelen ("type": "module"), en de interop-beperkingen (vooral CJS-kan-ESM-niet-require) voorkomt de veelgebruikte verwarring en fouten die ontstaan wanneer je ze mengt.