Sub topic 14
Loading ES Modules from CommonJS
This chapter assumes you know ES module syntax, async/await, and how Node.js decides whether a file is CommonJS or an ES module (the .cjs/.mjs extensions and the "type" field in package.json, covered earlier). It also assumes you know what a module namespace object is.
Many Node.js codebases are still CommonJS. They use require() and module.exports. More and more npm packages now ship only as ES modules. This chapter shows how CommonJS code can still use those packages. The main tool is import(), plus the newer require(esm) support in recent Node.js versions.
Why `require()` Has Trouble with ES Modules
require() is synchronous. It reads a file, runs it, and returns module.exports before the next line executes. ES modules were designed to load asynchronously. The loader can fetch files, link the graph, and pause evaluation for top-level await.
For years these two models did not mix. Calling require() on an ES module threw ERR_REQUIRE_ESM:
// old-node.cjs (Node.js 20.18 and earlier, without flags)
const { greet } = require('./greet.mjs');
// Error [ERR_REQUIRE_ESM]: require() of ES Module ./greet.mjs not supported.import() avoided the problem from the start. It is an expression that returns a promise, so it works the same way in both module systems. It is also available inside CommonJS files.
The Basic Pattern
Here is a small ES module and a CommonJS file that loads it:
// greet.mjs
export function greet(name) {
return `Hello, ${name}!`;
}
export default function shout(name) {
return greet(name).toUpperCase();
}// main.cjs (CommonJS)
async function main() {
const { greet } = await import('./greet.mjs');
console.log(greet('world'));
}
main();Run it with node main.cjs. It prints Hello, world!.
A CommonJS file cannot use top-level await, so the await has to sit inside an async function. Calling main() and dropping the returned promise works, but any error inside it becomes an unhandled rejection. A more careful entry point handles that:
// main.cjs
async function main() {
const mod = await import('./greet.mjs');
console.log(mod.greet('world'));
console.log(mod.default('world')); // the default export
}
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});The namespace object behaves the same way here as it does in an ES module. Named exports are properties, and the default export is the default property.
Exposing an ESM Dependency from a CommonJS Module
The hard part is usually not the entry point. It is a CommonJS module in the middle of your code that needs an ESM-only package and has synchronous callers.
You cannot make module.exports wait for a promise. You have two honest options. You can export an async function, or you can export a promise. The common approach is a cached loader:
// slugify-loader.cjs
let modulePromise = null;
function loadSlugger() {
if (modulePromise === null) {
modulePromise = import('./slugger.mjs');
}
return modulePromise;
}
async function slugify(text) {
const { toSlug } = await loadSlugger();
return toSlug(text);
}
module.exports = { slugify };// slugger.mjs
export function toSlug(text) {
return text.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}// app.cjs
const { slugify } = require('./slugify-loader.cjs');
slugify(' Dynamic Import & CommonJS ').then((slug) => {
console.log(slug); // dynamic-import-commonjs
});The module system already caches import() results, so storing the promise is not strictly needed. Storing it does skip repeated resolution work and keeps one obvious place to add a fallback. The cost of this pattern is that slugify becomes async, and so does every caller. If that change spreads through a large codebase, consider whether to convert the calling code to ESM.
`require(esm)` in Recent Node.js
Node.js 22.12 and 20.19 turned on support for calling require() on ES modules by default. It works when the whole ES module graph being loaded is synchronous, meaning nothing in it uses top-level await.
// sync-require.cjs (Node.js 20.19+ or 22.12+)
const ns = require('./greet.mjs');
console.log(ns.greet('world')); // named export
console.log(ns.default('world')); // default exportrequire() returns the namespace object, not the default export. This catches people who expect require() to hand back the function directly. If the ES module exports a name called "module.exports", Node.js returns that value instead. Library authors can use this to give CommonJS callers a cleaner value.
If any module in the graph uses top-level await, require() throws ERR_REQUIRE_ASYNC_MODULE. The synchronous loader has no way to wait. In that case import() is the only option.
| Approach | Works on | Synchronous | Top-level await in target | Returns |
|---|---|---|---|---|
| `require('./x.mjs')` | Node.js 20.19+, 22.12+ | Yes | Throws `ERR_REQUIRE_ASYNC_MODULE` | Namespace object |
| `await import('./x.mjs')` | All supported Node.js versions | No | Allowed | Promise for namespace object |
Use import() when you support older Node.js versions, when you cannot control whether a dependency adds top-level await later, or when lazy loading is the goal anyway. Use require(esm) when you control the runtime and need a synchronous value.
Resolution Differences to Watch For
import() inside a .cjs file uses the ESM resolver, not the CommonJS one. This changes several rules:
- File extensions are required for relative paths.
import('./greet')fails even thoughrequire('./greet')would findgreet.js. Writeimport('./greet.mjs'). - Directory
index.jslookup does not happen.import('./utils')does not load./utils/index.js. - Absolute paths should be URLs. On Windows,
import('C:\\app\\x.mjs')fails becauseC:looks like a URL scheme. Convert withpathToFileURL. - Package
exportsconditions differ.import()matches the"import"condition in a package'sexportsfield, andrequire()matches"require". A dual package can give you two different files, and two separate module instances.
// load-absolute.cjs
const path = require('node:path');
const { pathToFileURL } = require('node:url');
async function loadPlugin(file) {
const absolute = path.resolve(__dirname, file);
return import(pathToFileURL(absolute).href);
}
loadPlugin('greet.mjs').then((mod) => console.log(mod.greet('plugin')));Relative specifiers in import() resolve against the file that contains the call, just as they do in ES modules. They do not resolve against the current working directory.
The TypeScript Trap
TypeScript projects that emit CommonJS used to rewrite import() into Promise.resolve().then(() => require(...)). That rewrite reintroduces the original ERR_REQUIRE_ESM problem. You get CommonJS code that tries to require() an ESM-only package.
Set "module": "node16" or "nodenext" in tsconfig.json. With those settings TypeScript keeps import() as a real dynamic import in .cts and CommonJS output. Bundlers that output CommonJS can have the same issue. Check their output when an ESM-only dependency fails to load.
Interop in the Other Direction, Briefly
When an ES module imports a CommonJS file, module.exports becomes the default export. Node.js also tries to detect named exports by analysing the CommonJS source statically. Patterns like exports.foo = ... are found. Values assigned dynamically are not. That is why import { thing } from 'some-cjs-package' sometimes fails while import pkg from 'some-cjs-package' followed by pkg.thing works. When you load a CommonJS file with import(), the same rules apply to the namespace object you get back.
Exercise
A CommonJS file runs const chalk = require('chalk'); and fails with ERRREQUIREESM on Node.js 18. Chalk 5 is ESM-only and its main export is the default export. Rewrite the loading so it works on Node.js 18 and prints "ok" using chalk.green.
Show answer
Use import() inside an async function and read the default property: async function main() { const { default: chalk } = await import('chalk'); console.log(chalk.green('ok')); } main().catch((err) => { console.error(err); process.exitCode = 1; }); The require() call cannot work on Node.js 18, and the namespace object holds chalk under default, not at the top level.
Exercise
On Node.js 22.12, const ns = require('./db.mjs') throws ERRREQUIREASYNC_MODULE, but db.mjs itself has no await at the top level. What is the likely cause, and what is the fix?
Show answer
A module that db.mjs imports, directly or further down, uses top-level await. require(esm) needs the whole graph to be synchronous. Switch to const ns = await import('./db.mjs') inside an async function, or remove the top-level await from the dependency if you control it.
Exercise
Why does import('./helpers') fail inside a .cjs file when require('./helpers') loads helpers.js correctly?
Show answer
import() uses the ESM resolver even inside CommonJS. ESM resolution requires the full file extension and does no extension or index.js guessing, so the specifier must be './helpers.js'.