Sub topic 15
Mixing ES Modules and CommonJS
Most Node.js projects contain both module systems. Your own code may use import and export, while a dependency, an old internal file, or a build tool config still uses require() and module.exports. This chapter explains how Node.js connects the two systems, what each direction supports, and the errors you get when the rules are broken.
This chapter assumes you know how Node.js decides a file's format: .mjs files are ES modules, .cjs files are CommonJS, and .js files follow the nearest package.json "type" field. It also assumes you are familiar with default and named imports and with import.meta.url.
Two Systems with Different Timing
CommonJS (CJS) is Node.js's original module system. require() is an ordinary synchronous function. It runs the target file at the moment it is called and returns whatever that file assigned to module.exports. Node.js cannot know what a CJS module exports until the module has run.
ES modules work the other way. Imports and exports are declared statically, the whole graph is linked before any code runs, and evaluation can be asynchronous because of top-level await. Every interop rule below follows from this difference in timing.
| Feature | CommonJS | ES modules |
|---|---|---|
| Load syntax | `require('./x.cjs')` | `import x from './x.mjs'` |
| Export syntax | `module.exports = ...` or `exports.name = ...` | `export` declarations |
| When exports are known | After the module runs | At parse time |
| Loading | Synchronous | Asynchronous, may use top-level await |
| Bindings | Copies of property values | Live bindings |
| `__dirname`, `__filename` | Available | Not defined; use `import.meta` |
| File extension in specifiers | Optional | Required for relative paths |
Importing CommonJS from an ES Module
An ES module can import any CommonJS module. Node.js runs the CJS file and wraps the result in a module namespace.
The default import is module.exports
Whatever the CJS file assigns to module.exports becomes the default export. This always works, whatever shape the exports take.
// legacy.cjs
function greet(name) {
return `Hello, ${name}`;
}
module.exports = {
greet,
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.greet('Ada')); // Hello, Ada
console.log(legacy === sameLegacy); // true: the default import is module.exportsBoth paths return the same object because Node.js keeps one cached instance of legacy.cjs.
Named imports depend on static detection
You can often write import { greet } from './legacy.cjs'. Node.js supports this by scanning the CJS source text with a lexer before running the file. The lexer recognizes common patterns such as exports.greet = ..., module.exports.greet = ..., and module.exports = { greet, version } written as an object literal. It cannot see exports that are built at runtime.
// dynamic-exports.cjs
const api = {};
for (const name of ['start', 'stop']) {
api[name] = () => console.log(`${name} called`);
}
module.exports = api;// use-dynamic.mjs
// import { start } from './dynamic-exports.cjs';
// SyntaxError: Named export 'start' not found. The requested module
// './dynamic-exports.cjs' is a CommonJS module, which may not support
// all module.exports as named exports.
import api from './dynamic-exports.cjs';
const { start, stop } = api;
start(); // start called
stop(); // stop calledThe error message suggests the fix itself: import the default and destructure it. When a named import fails on a CJS package, use the default import.
Using require inside an ES module
ES modules have no require, module, exports, __filename, or __dirname. When you need require, for example to use require.resolve() or to load a file the way CJS would, create one with createRequire(import.meta.url), as main.mjs shows above. Paths passed to it resolve relative to the current module.
To replace __dirname and __filename, use import.meta.dirname and import.meta.filename (Node.js 20.11 and later). On older versions, call fileURLToPath(import.meta.url) from node:url.
Loading ES Modules from CommonJS
The other direction is harder because require() must return a value synchronously.
Dynamic import() works everywhere
import() is available in CommonJS files. It returns a promise for the module namespace, so the CJS code must handle the result asynchronously.
// report.mjs
export default function report(data) {
return `Report: ${data.length} items`;
}
export const format = 'text';// app.cjs
async function main() {
const { default: report, format } = await import('./report.mjs');
console.log(report([1, 2, 3])); // Report: 3 items
console.log(format); // text
}
main();This is the portable option. It works in every Node.js version that supports ES modules.
require() of an ES module
Node.js 22.12 and 20.19 also allow require() to load an ES module synchronously. The call returns the module namespace object, so the default export is under .default:
// app-sync.cjs
const reportModule = require('./report.mjs');
console.log(reportModule.default([1, 2])); // Report: 2 items
console.log(reportModule.format); // textThis only works if the ES module and all its dependencies avoid top-level await. A synchronous call cannot wait for a promise, so Node.js throws ERR_REQUIRE_ASYNC_MODULE when it finds top-level await in the graph. Older Node.js versions throw ERR_REQUIRE_ESM for any require() of an ES module.
Publishing Packages for Both Systems
A library that serves both ESM and CJS users can declare separate entry points with conditional exports:
{
"name": "geometry",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
}
}Node.js picks the "import" target for import and import(), and the "require" target for require(). Conditions are checked in the order they are written.
The dual package hazard
Shipping two builds means one application can load both copies. Suppose one dependency imports geometry and another requires it. Each build gets its own module instance, so you end up with two copies of the package's state. Singletons are duplicated, caches split, and instanceof checks fail across the two copies. You can reduce the risk in two ways:
- Make the ESM entry a thin wrapper that imports the CJS build and re-exports its values, so only one copy of the state exists.
- Ship only ESM and rely on
require(esm)for CJS consumers on current Node.js versions, as long as the package uses no top-level await.
Common Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
| `SyntaxError: Named export 'x' not found` | The CJS lexer could not detect `x` | Use the default import and destructure it |
| `ReferenceError: require is not defined in ES module scope` | `require` used in an ES module | Use `import`, or `createRequire(import.meta.url)` |
| `ReferenceError: __dirname is not defined` | CJS globals used in an ES module | Use `import.meta.dirname` or `fileURLToPath` |
| `ERR_REQUIRE_ESM` | `require()` of an ES module on older Node.js | Use `await import()` or upgrade Node.js |
| `ERR_REQUIRE_ASYNC_MODULE` | The required ES graph uses top-level await | Use `await import()` or remove the top-level await |
| `SyntaxError: Cannot use import statement outside a module` | A `.js` file with `import` is treated as CJS | Rename to `.mjs` or set `"type": "module"` |
Exercise
A CommonJS file contains module.exports = Object.assign({}, { parse, stringify });. An ES module writes import { parse } from './serializer.cjs'; and gets a SyntaxError. Explain why, and give the corrected import.
Show answer
Node.js finds named exports by scanning CommonJS source with a lexer that only recognizes simple patterns such as exports.name = ... or an object literal assigned to module.exports. A call to Object.assign is only resolved at runtime, so the lexer finds no named exports. The default import is always module.exports, so write import serializer from './serializer.cjs'; const { parse } = serializer;.
Exercise
A CommonJS script on Node.js 22.12 calls require('./db.mjs'), and db.mjs contains export const pool = await connect();. What happens, and how should the script load the module instead?
Show answer
The call throws ERR_REQUIRE_ASYNC_MODULE. require() is synchronous and cannot wait for the top-level await in db.mjs. Load the module with dynamic import inside an async function: const { pool } = await import('./db.mjs');.
Exercise
counter.cjs sets exports.count = 0 and exports an increment function that runs exports.count += 1. An ES module does import counter, { count, increment } from './counter.cjs'; increment();. What do count and counter.count contain afterward?
Show answer
count is still 0. Named exports from CommonJS are values Node.js copied once after the module ran, not live bindings. counter.count is 1, because the default import is the actual module.exports object that increment changed.