Importing CommonJS from ESM
What you'll learn: How ES modules can import CommonJS modules and what happens to their exports.
When you're working in an ES module (a .mjs file or a file in a package with "type": "module"), you can still import older CommonJS modules using the standard import syntax. Node.js handles this interoperability automatically, but there's an important detail about how CommonJS exports get wrapped.
How It Works
When you import a CommonJS module into an ES module, Node.js takes whatever was assigned to module.exports in that CommonJS file and makes it available as the default export.
Think of it like this: CommonJS modules don't have the concept of "named exports" the way ES modules do. They just have one thing—module.exports. So Node.js says, "Okay, I'll treat that one thing as your default export."
// old-logger.js (CommonJS)
module.exports = {
log: (msg) => console.log(msg),
warn: (msg) => console.warn(msg)
};
// app.mjs (ES Module)
import logger from './old-logger.js';
logger.log('Hello from ESM!');
logger.warn('Warning!');
Notice you use import ... from with a default import, not named imports with curly braces. The entire module.exports object becomes the default export.
Why This Matters
You cannot use named imports directly from most CommonJS modules because they don't explicitly define named exports. Node.js wraps the CommonJS export as a single default, so you must import it as such, then access properties from the imported object.
Key Takeaway: When importing CommonJS modules into ES modules, the entire module.exports value becomes the default export—use import name from './module.js' syntax to access it.