Named Exports Detection
You'll learn how Node.js tries to detect named exports from CommonJS modules when imported into ESM, and why this magic sometimes fails.
When you import a CommonJS module into an ES module, Node.js doesn't just wrap it as a default export and call it done. It actually analyzes the CommonJS code to see if it can extract named exports for you.
How Detection Works
Node.js performs static analysis on the CommonJS file, looking for patterns like exports.someName = ... or module.exports = { name1, name2 }. If it finds these patterns, it makes those names available as named imports in ESM:
// utils.cjs (CommonJS)
exports.add = (a, b) => a + b;
exports.multiply = (a, b) => a * b;
// app.mjs (ES Module)
import { add, multiply } from './utils.cjs';
// Works! Node detected the named exports
When Detection Fails
The analysis is static — it reads the code without executing it. If your exports are assigned dynamically or conditionally, detection fails:
// dynamic.cjs
if (Math.random() > 0.5) {
exports.value = 42;
}
// app.mjs
import { value } from './dynamic.cjs';
// Error! Node couldn't detect 'value' statically
You'll need to use the default export wrapper instead:
import dynamicModule from './dynamic.cjs';
// Works, but you get the whole exports object
Think of it like a librarian cataloging books by reading their covers — they can only list what's printed there, not what might be written inside under certain conditions.
Key Takeaway: Node.js detects named exports from CommonJS through static analysis of simple assignment patterns; dynamic or conditional exports require using the default import approach.