Skip to content

Lesson 1 of 9 · 24m

ESM and CommonJS Interop Without Folklore

What actually happens when import meets require, why dual packages hurt, and the practical rules for making mixed dependency graphs behave.

The longest-running incident I have debugged in the Node ecosystem was not a memory leak or a race condition. It was a package graph where one dependency was CommonJS, one was ESM, one was both depending on how you imported it, and the bundler decided to instantiate two copies of the same library. Authentication state lived in copy A while the request handler read copy B. Everything typechecked. Nothing worked.

Node decides module format before it reads your code

The loader uses the nearest package boundary:

{
  "name": "orders-api",
  "type": "module",
  "main": "./dist/index.js"
}

With "type": "module", .js files are ESM. Without it, .js files are CommonJS. .mjs is always ESM and .cjs is always CommonJS. This is not a preference; it is resolution metadata. A file that uses import in a CommonJS package is a syntax error, not a flexible script.

The important consequence: changing "type" is a breaking repository-wide decision. Every .js file changes semantics at once.

ESM can import CommonJS, but named exports are heuristic

// consumer.mjs
import legacy from "legacy-lib";
import { createClient } from "legacy-lib";

A CommonJS module becomes a default export shaped like module.exports. Node also performs static analysis on the source and tries to synthesize named exports. That works for simple assignments:

module.exports.createClient = createClient;
exports.version = "4.2.0";

It fails when exports are computed:

for (const name of methods) exports[name] = makeMethod(name);

Then import { createClient } fails even though legacy.createClient exists at runtime. The fix is usually import pkg from "legacy-lib"; const { createClient } = pkg;, not rewriting your application around a fantasy of perfect interop.

CommonJS cannot require ESM — except when it now can

Historically require() of an ES module threw ERR_REQUIRE_ESM, pushing everyone into dynamic await import(). Modern Node supports synchronous require() for synchronous ESM graphs in recent releases, but you cannot build a production support policy on “recent.” If you maintain a library consumed by old LTS lines, assume the old rule unless you control the runtime floor.

Dynamic import is still the robust bridge:

async function loadPlugin(path) {
  const mod = await import(pathToFileURL(path).href);
  return mod.default ?? mod;
}

Use pathToFileURL; passing a Windows path or an unescaped pathname directly to import() is a portability bug.

The dual-package hazard is the real enemy

A dual package ships both formats:

{
  "exports": {
    ".": {
      "import": "./dist/esm/index.js",
      "require": "./dist/cjs/index.cjs"
    }
  }
}

This is useful for compatibility, but dangerous when the package has identity-sensitive state. Two module instances mean two singletons, two class objects, and sometimes two copies of dependencies. instanceof starts lying. Configuration is applied in one copy and ignored in the other.

The mitigation is boring: pick one format for application code, force dependency versions into alignment with a lockfile, and make libraries with shared state small enough that duplication cannot matter.

Field notes

  • node --input-type=module -e "..." is for snippets; it does not change how files are interpreted.
  • __dirname and __filename do not exist in ESM. Use fileURLToPath(import.meta.url).
  • ESM specifier resolution requires extensions: ./client.js, not ./client, unless a loader or bundler is rewriting behavior.
  • If a bug says configuration was set but “not picked up,” inspect node_modules for duplicated copies before blaming cache logic.
  • Do not dual-publish private application packages unless an external consumer truly needs both formats.

Was this lesson helpful?

Sign in to rate