Question presented to candidate: "A file uses import/export syntax and another uses require()/module.exports in the same project. What determines which system a given file uses, and can the two actually interoperate?"
What a strong answer should cover:
- Node supports two distinct module systems: CommonJS (CJS) —
require()/module.exports, synchronous, Node's original system — and ES Modules (ESM) —import/export, the standard JavaScript module system, asynchronous-capable, file-extension- orpackage.json-determined. - Which system a
.jsfile uses is decided bypackage.json's"type"field:"type": "module"makes.jsfiles ESM; its absence (or"type": "commonjs") makes them CJS. The explicit extensions.mjs(always ESM) and.cjs(always CJS) override thepackage.jsonsetting file-by-file, regardless of"type". - 📌 A verifiable, not just documented, distinction:
requireis genuinely undefined inside a real ESM file — calling it throws aReferenceError, not a discouraged-but-working fallback. - ESM importing CJS works one direction cleanly: a default import receives the entire
module.exportsobject. A named import additionally works for properties Node's static analysis (cjs-module-lexer) can detect as simple assignments — but this is a best-effort heuristic, not a full guarantee, for dynamically-computed CJS exports. - CJS
require()-ing ESM used to be impossible entirely (only dynamicimport()worked); modern Node (from Node 22, broadening in later releases) allowsrequire()to load a synchronous ES Module directly, with one hard exception (top-levelawait) — covered with its own live verification in the dedicatedrequire(esm)question. - A precise answer keeps CJS and ESM's caching mechanisms conceptually distinct even though both cache: CJS keys its cache by resolved file path; ESM's module registry keys by resolved URL — this matters for edge cases like the same file reached via different URL forms.
Clarifying questions expected:
- "Is the codebase fully ESM, fully CJS, or a mix?" — decides how much of the interop-specific detail actually matters here.
- "Is the concern about how to WRITE interop code, or just understanding which system a given file uses?" — different depths of the same topic.
Code / implementation expected: Yes — showing a real ESM file importing a CJS file (and vice versa, referencing the dedicated require(esm) question) with the actual observed export shapes is the concrete, convincing version of this answer.