require() ES modules from CommonJS
Use require() to read a synchronous ESM namespace from CommonJS, and recognize when top-level await means you need dynamic import.
You have a CommonJS script that needs a function from an ES module. Use require() for the synchronous case and read the default export from the namespace it returns.
Read the export from the namespace
Node 22.12 enabled require(esm) by default on the 22 line. Save the ES module below as format.mjs.
export default function formatVenue(name) {
return name.toUpperCase()
}The ES module exports the formatter as its default value.
Save this consumer as read.cjs beside it. The extensions tell Node which module format each file uses.
const { default: formatVenue } = require('./format.mjs')
console.log(formatVenue('Hall A'))Run node read.cjs and the script prints HALL A.
In this example require() returns the module namespace. The function is on its default property. If you write const formatVenue = require('./format.mjs') and call that binding, you call the namespace object and get a TypeError. For a named export, read the matching property from the namespace.
Switch to import() for top-level await
Replace format.mjs with this version and run the same CommonJS script. The module must wait for prefix before the export can use it.
const prefix = await Promise.resolve('Venue: ')
export default function formatVenue(name) {
return prefix + name.toUpperCase()
}The require() call throws ERR_REQUIRE_ASYNC_MODULE because the module uses top-level await.
diagram
Require checks the whole module graph
If format.mjs has no top-level await, follow its static imports for the source of the error. An await inside an exported async function runs when you call the function.
From CommonJS, you can use import('./format.mjs') and await that promise in an async function. The dynamic import can wait for the graph before resolving to the namespace. You can try node -e "import('./format.mjs').then(m => console.log(m.default('Hall A')))" to see Venue: HALL A.
For a package name, have Node load the exact specifier you plan to ship. A package's exports map can pick different entry points for require and import. Check the public entry points if Node reports ERR_PACKAGE_PATH_NOT_EXPORTED.