← Back to Node.js, page 7

nodejs-0126 · Hard senior

What is the dual package hazard, and how do you publish a package for both CommonJS and ESM without it?

If a package ships separate CommonJS and ES module builds, an app can load both, and then the package exists twice in memory with separate state, caches and class identities. instanceof checks and singletons break. Avoid it by shipping ESM only (modern Node can require() ES modules), by making the ESM file a thin wrapper around the CommonJS build, or by keeping all state in one shared file.

Full answer

The problem

  • A package with exports { import: './index.mjs', require: './index.cjs' } resolves to different files for import and require.
  • If one part of the app uses import and another (maybe a dependency) uses require, Node loads both files. Module level state is created twice: two caches, two counters, two singletons. A class has two identities, so instanceof fails across the boundary.
  • Bugs appear only in mixed applications, so tests of each format separately pass.

Solutions

  1. ESM only. Node supports require() of ES modules (unflagged since 22.12 and in 24, without top-level await in the graph), so a CommonJS consumer can still load the package. This is now the simplest option for new packages. Drop support for old Node versions.
  2. Wrapper: write the logic in CommonJS and ship a small ESM file that imports the CommonJS file and re-exports the names. There is one copy of the state. The drawback is that named exports must be listed by hand.
  3. Stateless dual build: allow two copies when the package has no state and no classes that are compared with instanceof (pure functions).
  4. Isolate state in a third file that both builds import (a single shared CommonJS module).

Other checks

  • Use the exports field with types conditions first for TypeScript.
  • Test with a mixed consumer in CI (a script that imports and requires the package and checks identity).
  • Document the supported Node versions and formats.
  • Symbol.for-based registries can share state on purpose when a duplicate cannot be avoided.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dual-'));
const write = (file, text) => { fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); fs.writeFileSync(path.join(dir, file), text); };
const pkg = (name, exportsField) => write(`node_modules/${name}/package.json`, JSON.stringify({ name, exports: exportsField }));

// 1. Two separate builds, each with its own counter (the hazard).
pkg('dual-bad', { import: './index.mjs', require: './index.cjs' });
write('node_modules/dual-bad/index.mjs', 'let n = 0; export const inc = () => ++n; export class Box {}');
write('node_modules/dual-bad/index.cjs', 'let n = 0; exports.inc = () => ++n; exports.Box = class Box {};');

// 2. ESM wrapper around one CommonJS core (one copy).
pkg('dual-wrapper', { import: './index.mjs', require: './index.cjs' });
write('node_modules/dual-wrapper/index.cjs', 'let n = 0; exports.inc = () => ++n; exports.Box = class Box {};');
write('node_modules/dual-wrapper/index.mjs', "import core from './index.cjs'; export const { inc, Box } = core;");

// 3. ESM only, loaded by require() as well.
pkg('esm-only', { default: './index.js' });
write('node_modules/esm-only/package.json', JSON.stringify({ name: 'esm-only', type: 'module', exports: './index.js' }));
write('node_modules/esm-only/index.js', 'let n = 0; export const inc = () => ++n; export class Box {}');

write('check.mjs', `
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
for (const name of ['dual-bad', 'dual-wrapper', 'esm-only']) {
  const esm = await import(name);
  const cjs = require(name);
  esm.inc();
  const sharedState = cjs.inc() === 2;      // 2 means both sides count in the same variable
  const sameClass = esm.Box === cjs.Box;
  console.log(name.padEnd(13), 'shared state:', sharedState, '| same class:', sameClass);
}
`);

const run = spawnSync(process.execPath, ['check.mjs'], { cwd: dir, encoding: 'utf8' });
process.stdout.write(run.stdout);
if (run.status !== 0) console.log(run.stderr);
fs.rmSync(dir, { recursive: true });

Three small packages are created. Each one is loaded through import and through require, and the script checks whether state and classes are shared. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): dual-bad shared state: false | same class: false dual-wrapper shared state: true | same class: true esm-only shared state: true | same class: true

Key points

  • Two builds can mean two copies of state and classes.
  • instanceof and singletons break across copies.
  • ESM only plus require(esm) is the simplest modern answer.
  • A CommonJS core with an ESM wrapper keeps a single copy.
  • Test with a mixed import and require consumer.

Common mistakes

  • Testing only the ESM build or only the CommonJS build.
  • Putting singletons or caches in both builds.
  • Comparing classes with instanceof across the two copies.
  • Forgetting the types condition order in exports.
  • Dropping CommonJS support without telling users which Node version is needed.

Follow-ups

  • Why can require() of an ES module fail if it uses top-level await?
  • How does the module-sync condition help?
  • How do you test a package in both formats in CI?

Tips

  • Explain 'two copies in memory' in one sentence.
  • Give two fixes.
  • Mention testing with a mixed consumer.