Sub topic 15
Mixing ES Modules and CommonJS
This chapter assumes you know how Node.js decides whether a file is an ES module, through the .mjs and .cjs extensions or the "type" field in package.json. It also assumes you know default imports and import.meta.url. Many npm packages still use CommonJS (CJS), the older format with require() and module.exports, so you will often need both formats in one program.
Importing CommonJS from an ES module
An ES module can import a CommonJS module with an ordinary import statement. Node.js runs the CJS file, and its module.exports object becomes the default export.
// legacy.cjs
module.exports = {
greet(name) {
return `Hello, ${name}`;
},
version: '2.1.0',
};// main.mjs
import { createRequire } from 'node:module';
import legacy from './legacy.cjs';
const require = createRequire(import.meta.url);
const sameLegacy = require('./legacy.cjs');
console.log(legacy === sameLegacy); // true: the default import is module.exports
console.log(legacy.greet('Ada')); // Hello, AdaNode.js also tries to provide named imports from CJS. It scans the CJS source for patterns such as exports.version = ... or module.exports = { version: ... }. If the scan finds a name, import { version } from './legacy.cjs' works. If the exports are built dynamically, for example in a loop or by calling a function, the scan misses them, and the named import fails with a SyntaxError. The default import always works, so use it when you are unsure.
Using require inside an ES module
ES modules do not have require, module, exports, __filename, or __dirname. When you need require, for example to load a file synchronously or to call require.resolve, create one with createRequire(import.meta.url) as shown above. For paths, use import.meta.filename and import.meta.dirname (Node.js 20.11 and later), or fileURLToPath(import.meta.url) on older versions.
Loading ES modules from CommonJS
CommonJS loads modules synchronously, while ES modules can load asynchronously. That difference sets the rules:
| Approach | Works when |
|---|---|
| `await import('./esm.mjs')` | Every Node.js version that supports ESM |
| `require('./esm.mjs')` | Node.js 20.19+ or 22.12+, and only if the module graph has no top-level `await` |
// app.cjs
async function main() {
const { area } = await import('./math.mjs');
console.log(area(2));
}
main();If require() reaches an ES module that uses top-level await, it throws ERR_REQUIRE_ASYNC_MODULE. Dynamic import() handles that case.
Common errors
ReferenceError: require is not defined in ES module scope: useimport, or createrequirewithcreateRequire.__dirname is not defined: useimport.meta.dirname.- Named export not found: the CJS module builds its exports dynamically. Use the default import.
ERR_REQUIRE_ESMon older Node.js: replacerequire()withawait import().
Exercise
A CommonJS file does module.exports = makeApi();, where makeApi returns { start, stop }. In an ES module, import { start } from './api.cjs' throws a SyntaxError. Why, and how do you fix it?
Show answer
Node.js finds named exports by scanning the CJS source without running it, so it cannot see the names returned by a function call. Import the default export instead: import api from './api.cjs'; const { start } = api;.
Exercise
A CommonJS script calls require('./config.mjs') on Node.js 22.12, and config.mjs uses top-level await. What happens, and what should the script do instead?
Show answer
require() throws ERRREQUIREASYNC_MODULE because it cannot load an asynchronous module graph synchronously. Use const config = await import('./config.mjs'); inside an async function.