· By John Kavanagh

Testing CommonJS and ESM Consumers Before Publishing a Node Package

Photograph of two brown cardboard presentation boxes on a matching background.
Image by Mildlee, licensed from Unsplash.

A package's own tests can pass whilst its published entry point refers to a file which isn't in the package. They can also pass whilst CommonJS consumers receive a different API from ESM consumers, or whilst the two entry points quietly create separate copies of supposedly shared state.

Those are awkward discoveries to leave to somebody installing the release.

I start this check by packing the package and installing that tarball into a small consumer project. The consumer imports the package by its public name. No source alias, workspace shortcut, or test‑runner transformation is allowed to help it find the right answer.

My earlier guides to CommonJS and ES modules cover the syntax. Here, the question is whether an installed package keeps its promises to both kinds of caller.


Write down the Consumer Contract

For this example, the package normalises a small set of local route strings. Both loaders should expose a named normaliseRoute function, and both should reach the same mutable registry. A call counter makes that second requirement easy to observe.

The registry is deliberately artificial. A real package might have registered plugins, shared configuration, a cache, or class instances whose identity matters. The point is to choose something that would reveal two copies of the implementation, rather than merely checking that both copies return the same string.

List the supported package specifiers as well. The root import and a public normalise subpath belong to this contract. An internal distribution file does not. Once an exports map is introduced, previously reachable deep imports may stop working, so inspect existing consumer usage before describing the change as harmless.


Inspect What Actually Gets Packed

Packing should happen after producing the distribution files, using the same file‑selection rules as the intended release. Inspect the tarball's file list before installing it. A correct exports target still needs an actual file at the other end.

Create separate consumer directories for CommonJS, ESM, and a process which uses both. Give them a local tarball dependency and their own installation state. For this synthetic package there are no remote runtime dependencies, so installation can run with network access disabled and an isolated cache.

I also check the resolved path. It must point inside the consumer's installed package, rather than back into the producer checkout. Otherwise, we're testing the checkout again, without checking that the same files made it into the package.

Keep the tarball hash, manifest, installed path, and runtime version with the result. They make a failed release much easier to compare with the artefact that actually passed.


Export Conditions are Ordered

A simplified map for the two entry points looks like this:

{
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs",
      "default": "./dist/index.mjs"
    },
    "./normalise": {
      "import": "./dist/normalise.mjs",
      "require": "./dist/normalise.cjs"
    }
  }
}

Node's package documentation specifies that matching conditions are considered in property order. Put the generic default fallback last. Moving it above import and require can cause both consumers to select the fallback before reaching the entries intended for them.

Test that failure deliberately. Give the fallback a distinguishable export and check which implementation each consumer receives. The file loading successfully is only the beginning; its function names, return values, and selected behaviour must match the contract.

Custom conditions need the same treatment. If the package has a development entry, launch the consumer with --conditions=development and assert that it selected that entry. A test which never enables the condition doesn't tell us much about it.


Test Both Loaders in the Same Process

Separate smoke tests miss the most interesting failure in this example. The CommonJS build can increment its registry correctly, and the ESM build can increment its own registry correctly. Both tests pass. The application still has two registries.

The combined consumer makes the requirement explicit:

import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const cjs = require('@lab/routes-shared-cjs');
const esm = await import('@lab/routes-shared-cjs');

assert.strictEqual(cjs.registry, esm.registry);
assert.strictEqual(cjs.normaliseRoute, esm.normaliseRoute);
cjs.normaliseRoute('/catalogue/');
assert.equal(esm.registry.calls, 1);

For the corrected dual‑entry version, I keep one CommonJS implementation and make the ESM entry a thin wrapper which re‑exports its function and registry. That preserves the references under test. The wrapper does not initialise another registry or copy its current contents into a new object.

I wouldn't impose shared object identity on every package. Two independent copies of a genuinely stateless utility may be acceptable. But that should be an explicit decision. A counter is a convenient teaching example precisely because it refuses to let us confuse equal results with shared state.


Be Precise About Node's Newer Interoperability

Node 22.12 enabled loading eligible ES modules with require() by default. The feature is still described as release‑candidate functionality in the Node 22.13 documentation. Node 22.13, released this month, also stops emitting the experimental warning by default.

That warning change is worth recording, but it doesn't change the package contract. A quiet process can still load the wrong export.

For a package whose supported runtime range permits it, the module-sync condition can direct both loaders to one synchronous ESM implementation. The consumer still needs to check the returned namespace shape; being able to call require() does not automatically preserve an older module.exports = someFunction interface.

The entire loaded graph must be synchronous. If a dependency introduces top‑level await, a require() call can fail with ERR_REQUIRE_ASYNC_MODULE even when the entry file contains no await. Test an asynchronous dependency as well as the straightforward synchronous case. An ESM import may still succeed, which is exactly why one consumer cannot stand in for both.


Keep the Negative Cases

The useful release check includes a few deliberately broken packages:

  • Remove a required distribution file and expect the appropriate missing‑module error.
  • Put default first and expect the entry‑selection assertion to fail.
  • Give CommonJS a function where the contract expects a named function on an object.
  • Build two independent registries and expect the combined consumer to reject them.
  • Add top‑level await in a dependency and expect the synchronous loader to reject the graph.

Also assert that the packed private file is rejected as a package subpath with ERR_PACKAGE_PATH_NOT_EXPORTED. That checks the supported import surface; it isn't filesystem security against somebody deliberately reaching an absolute path.

Check error codes and the behaviour under test rather than matching an entire stack trace. Preserve warnings as evidence, but don't turn their absence into the definition of compatibility.


Wrapping Up

Before changing a package's module format, I want a passing consumer matrix for the supported runtime range and the exact packed artefact. That includes the callers using both loaders together, not just the neat examples using one at a time.

Then choose the migration deliberately: retain a shared implementation, accept well‑understood stateless duplication, or raise the supported runtime floor for a synchronous ESM entry. The tests should explain what that choice preserves and what it breaks before the release makes the explanation somebody else's problem.

Postscript

March 2025: Node 20.19 has also enabled require(esm) by default and removed its default experimental warning. That widens the available runtime options, but it doesn't remove the synchronous‑graph restriction. Check the supported minor version, not just "Node 20".

November 2026: I've added my packed‑package lab with the passing and deliberately broken variants described above. I've checked its consumers on Node 22.12.0, 22.13.0, 22.23.5, and 24.14.0, using Yarn 4.18.1 for the local packaging and installation checks. The download keeps each consumer separate and records the actual runtime and package bytes, so you can adapt the checks to your own exports.

Downloadable Resource

  • Node.js Package Exports Lab

    Test local package tarballs with CommonJS, ESM, and combined consumers, including conditional exports, missing files, shared state, and asynchronous graphs.

    Download ZIP

Want to find out more?

If you need senior hands‑on support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.