Importing CJS from ESM
What you'll learn: How ES Modules can import CommonJS modules and what gotchas await you at the border between these two systems.
The Cross-System Bridge
Now that you know both ESM and CommonJS exist side-by-side (especially in Node.js), you'll frequently need to import a CommonJS module from an ES Module. Good news: this mostly works. The challenge is that ESM expects named exports, while CommonJS typically exports one big object via module.exports.
The Default Import Pattern
When you import a CommonJS module from ESM, the entire module.exports object becomes the default export:
// math.cjs (CommonJS file)
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// app.mjs (ES Module)
import math from './math.cjs';
console.log(math.add(5, 3)); // 8
You cannot use named imports directly:
import { add } from './math.cjs'; // ❌ Won't work!
Workarounds
If you really want destructuring, do it after the import:
import math from './math.cjs';
const { add, subtract } = math; // ✅ Works
The Caveat
This default-only behavior means ESM treats the entire CommonJS export as a single package. There's no way to selectively import parts for tree-shaking benefits, and you lose the clarity of named imports at the module boundary.
Key Takeaway: ESM can import CommonJS modules, but only as default imports—the entire module.exports becomes the default, requiring you to destructure afterward if you want individual pieces.