Learn JavaScript
❯ errors_modules.commonjs

CommonJS & Interop (Node.js) in JavaScript

$concept

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.

$how it works
1

require loads synchronously

const fs = require("fs") — cached, scoped, circular-tolerant module loading that built Node's ecosystem.

2

type field decides

package.json "type": "module" makes .js ESM; otherwise CJS — .mjs/.cjs force either regardless.

3

ESM imports CJS

import pkg from "cjs-lib" works (default mapping) — the common direction, well supported.

4

CJS needs dynamic import for ESM

require("esm-lib") throws — const m = await import("esm-lib") bridges synchronously-impossible gaps.

$example
// cjs-lib.js (CommonJS): module.exports = { v: 1 };
// app.mjs (ESM): import pkg from "./cjs-lib.js";
// console.log(pkg.v);
Output
1
1The CJS module assigns its public value to module.exports.
2ESM default-imports it — the supported interop direction.
31 prints across module systems — ecosystems cooperating.
$use cases
Reading legacy and npm packages written in CommonJS
Choosing module type per project via package.json
Bridging directions correctly (static vs dynamic import)
Writing new code as ESM while consuming CJS dependencies

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.