CommonJS & Interop (Node.js) in JavaScript
CommonJS (require/module.exports) powered Node before ESM: const x = require("./a") loads synchronously with per-module scope, caching, and circular-tolerance — still dominant in the npm ecosystem. Interop runs both ways: ESM imports CJS (default export mapping, named via static analysis), while CJS requires ESM only through dynamic import().
Node decides by nearest package.json type ("module" for ESM, else CJS) plus extensions (.mjs/.cjs overrides). New code writes ESM; legacy and many packages remain CJS — fluency in both plus the interop table is mandatory Node literacy.
require loads synchronously
const fs = require("fs") — cached, scoped, circular-tolerant module loading that built Node's ecosystem.
type field decides
package.json "type": "module" makes .js ESM; otherwise CJS — .mjs/.cjs force either regardless.
ESM imports CJS
import pkg from "cjs-lib" works (default mapping) — the common direction, well supported.
CJS needs dynamic import for ESM
require("esm-lib") throws — const m = await import("esm-lib") bridges synchronously-impossible gaps.
// cjs-lib.js (CommonJS): module.exports = { v: 1 };// app.mjs (ESM): import pkg from "./cjs-lib.js";// console.log(pkg.v);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.