Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 133 ยท Modules and Packages

Mixing ESM and CommonJS

How ES modules and CommonJS work together in Node.js 24 - importing CJS from ESM, require(esm), createRequire, dual packages, the exports field, default-export pitfalls and JSON imports.

Real projects rarely live in one module world. Your new code is ESM, but it depends on a package published as CommonJS. Or you maintain an old CommonJS service and a library you need has gone ESM-only. For years this was painful, and you will find many scary blog posts about it. In Node.js 24 it is much better: most combinations simply work. This lesson shows what works, the few rules that still bite, and how to publish a package that serves both worlds.

If you have not read them yet, start with ES Modules and CommonJS Modules. Everything below builds on them. As before, examples write small files to disk and then load them, so one editor tells the whole story. Snippets that start with // cjs run as CommonJS.

ESM importing CommonJS

An ES module can import a CommonJS file. Node runs the file and uses its module.exports as the default export. It also tries to find named exports, by scanning the CommonJS source for patterns like exports.name = ... (a static analysis step, so it is a best effort and not a guarantee).

Node.js Importing CommonJS from ESM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The default export is always the whole module.exports object (or function). Names like a and b were detected because the code uses the exports.name = pattern. When a CommonJS file builds its exports dynamically, the scan finds nothing and only the default is reliable:

Node.js When named exports are not detected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

ns.x is undefined because the scan could not see x. The safe habit when importing a CommonJS package is to use the default import and destructure from it:

NODE
import pkg from 'some-cjs-package';
const { helper } = pkg;

Static named imports such as import { helper } from 'some-cjs-package' often work, but a package update that changes how it writes its exports can break them with a SyntaxError at load time.

The __esModule pitfall

Tools like Babel and the TypeScript compiler (when targeting CommonJS) compile export default x into exports.default = x and add exports.__esModule = true as a marker. When ESM imports such a file, Node does not honour the marker. The default import is the whole module.exports object, not exports.default.

Node.js The double-default problem

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because Node treats the whole module.exports as the default, you have to write ns.default.default to reach the author's intended default. This is why many libraries now publish true ESM, and why bundlers have an "interop" setting. If you meet default.default in your own code, this is the cause. Newer Node versions also expose a 'module.exports' name on the namespace so that tools can reach the raw module.exports unambiguously.

CommonJS loading ES modules: require(esm)

The classic rule was "you cannot require() an ES module", because require is synchronous and ES modules could be asynchronous. In Node 22.12 and later (and so in Node 24 LTS), require() can load an ES module as long as nothing in its import graph uses top-level await. You get the namespace object back.

Node.js require() of ESM and the top-level await limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second require fails with ERR_REQUIRE_ASYNC_MODULE because the file uses top-level await, which cannot be waited for synchronously. The fix is to use import() instead, which returns a promise and handles everything. This feature is why many package authors can now publish ESM-only: their CommonJS users can still require() them. Check process.features.require_module if you want to know whether your Node supports it.

The rule of thumb: keep library entry points free of top-level await if you want them usable from require.

import() from CommonJS

import() has worked from CommonJS since early on and is the classic bridge. It is asynchronous, so you can only use the result after await or .then:

JavaScript
// in a .cjs file or a "type": "commonjs" project
async function main() {
  const { default: chalk } = await import('chalk');
  console.log(chalk.green('ok'));
}
main();

If an ESM-only package is imported from CommonJS this way, the code that uses it must become async. For a deeper discussion of async patterns see async/await Patterns.

createRequire: require inside ESM

Sometimes an ES module needs require: to load a JSON file the old way, to call require.resolve, or to load a .node native addon. ES modules have no require, but you can make one for the current file with createRequire.

Node.js createRequire in an ES module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

createRequire takes a URL or path that serves as the base for resolution; import.meta.url means "relative to this file". Treat it as an escape hatch, not a style: if you find yourself using it everywhere, a plain import or import() is probably better.

JSON modules and import attributes

ES modules cannot load JSON with a bare import. Since JSON can be dangerous to treat as code, the standard requires you to say what you expect with an import attribute: with { type: 'json' }.

Node.js Importing JSON with an import attribute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The JSON arrives as the default export (there are no named exports for JSON). The static form is import config from './config.json' with { type: 'json' };. Without the attribute, Node refuses with ERR_IMPORT_ATTRIBUTE_MISSING. Older Node versions used assert { type: 'json' }; that keyword was replaced by with, so always use with in Node 22 and later. Import attributes are a general mechanism, so future module types (CSS, for example) use the same syntax.

Packages and the exports field

When you import 'dual' or require('dual'), Node looks into node_modules/dual/package.json. A modern package uses the "exports" field to say which files are public and, with conditions, which file to give to which kind of caller. The two most important conditions are import (given to ESM importers) and require (given to CommonJS callers). This is how a package can ship both versions: a dual package.

Node.js A dual package built by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same package name delivers different files depending on how it is loaded. The last import shows the other half of "exports": anything not listed is private. Reaching into dist/index.cjs directly fails with ERR_PACKAGE_PATH_NOT_EXPORTED, so internal files can be reorganised without breaking users. The next lessons, package.json and the npm Registry and Creating and Publishing Packages, go further.

The dual package hazard: if an application loads both builds of the same package (some code imports it, other code requires it), they are two separate module instances with separate state. A class used with instanceof, a singleton, or a cache will behave as if there were two copies, because there are two. Authors avoid it by keeping state in one shared file, or by shipping a single format.

Which file is CommonJS, which is ESM?

The decision always depends on the file, not the whole project:

File Format
.mjs ESM
.cjs CommonJS
.js Depends on the nearest package.json "type" field ("module" or "commonjs", default commonjs)

You can have .cjs and .mjs files side by side in the same folder. In a project with "type": "module", name configuration files that must be CommonJS with the .cjs extension. In a CommonJS project, name ES modules .mjs. Node 22.7 and later also tries to detect ESM syntax in an ambiguous .js file and reruns it as ESM, but that is a convenience to avoid depending on.

Loaders and hooks, briefly

Node also lets you customise how modules are found and loaded, for example to run TypeScript or to resolve special specifiers. The API is module.register() (hooks running on a separate thread) and the newer module.registerHooks() (in-thread, synchronous hooks, which also affect require). You rarely write these yourself, but tools like test runners and TypeScript runners use them. TypeScript in Node.js shows the built-in way to run .ts files without any loader.

Practical advice

  • Write new code as ESM. Name the project "type": "module".
  • When you import a CommonJS package, use the default import and destructure from it if a named import fails.
  • Keep library entry points free of top-level await so require() keeps working.
  • Use createRequire and import() as bridges, not as the main style.
  • When publishing, prefer a single ESM build with a clean exports map, or a dual build whose state lives in one place.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A CommonJS file does module.exports = function f() {}. What is its default import from an ES module?

    When ESM imports a CommonJS file, the whole module.exports value becomes the default export.
  2. 2. In Node.js 24, what makes require('./lib.mjs') throw ERR_REQUIRE_ASYNC_MODULE?

    require() is synchronous, so it can only load an ES module graph that finishes evaluating without waiting. Top-level await breaks that. Use import() instead.
  3. 3. How does an ES module get a working require function?

    createRequire from node:module builds a require function that resolves relative to the URL you pass, usually import.meta.url.
  4. 4. What is needed to import a JSON file from an ES module in Node 24?

    JSON modules require the import attribute with { type: 'json' }. Without it Node throws ERR_IMPORT_ATTRIBUTE_MISSING. The data is the default export.
  5. 5. In package.json, what does an exports map with import and require conditions let a package do?

    Conditions pick the file by how the package is loaded, and any path that is not listed in exports cannot be reached from outside.

Summary

  • ESM can import CommonJS: module.exports becomes the default export, and named exports exist only when Node's static scan can see them.
  • Code compiled from TypeScript or Babel with __esModule can give you default.default; Node does not apply that marker.
  • In Node 22.12+ require() can load ES modules without top-level await; otherwise it throws ERR_REQUIRE_ASYNC_MODULE and you use import().
  • createRequire(import.meta.url) gives an ES module a require; import() lets CommonJS load ESM asynchronously.
  • JSON needs with { type: 'json' } when imported from ESM; require loads JSON freely.
  • The exports field with import and require conditions makes dual packages and keeps unlisted files private; beware loading both copies of a stateful package.
  • .mjs and .cjs are explicit; .js follows the nearest package.json type.

Next: package.json and the npm Registry explains the file that describes every Node.js project and package.