ESM vs CommonJS in a Large TypeScript Monorepo – What Works?

Context: Our team maintains a monorepo with ~30 packages, all written in TypeScript. We started with CommonJS (module.exports) because tsc emitted .js files that Node could run out‑of‑the‑box. Recently we switched a few packages to native ESM (export … and "type":"module" in package.json) to take advantage of tree‑shaking and the upcoming Node ecosystem.

Pros of staying on CommonJS

  • ts-node works without extra flags.
  • Inter‑package imports are simple (require('../utils')).
  • All existing tooling (Jest, Mocha, ts-node-dev) expects CJS.

Pros of moving to ESM

  • Native import/export works with browsers and bundlers without transpiling.
  • Better static analysis; circular‑dependency errors are caught earlier.
  • Allows mixed‑type imports (import pkg from 'pkg' vs require).

Pain points we hit

  • Dual package.json entries (exports field) to support both consumers.
  • Need a build step that emits both .cjs and .mjs files, increasing CI time.
  • Some internal scripts still rely on __dirname, which behaves differently in ESM.
{
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    }
  }
}

We experimented with tsc --module esnext and Babel to rewrite imports, but source‑map accuracy suffered. Using ts-node-esm solved runtime issues but slowed down test suites. Another option is to keep a single tsconfig.json with module: esnext and let the build produce only ESM, then rely on tools like esbuild to generate CJS shims for legacy consumers.

Open questions

  1. In a monorepo, is it worth maintaining two output formats, or should we enforce a single module system and migrate everything at once?
  2. Which CI/CD patterns have you found reliable for keeping type‑checking, linting, and test runs fast when mixing ESM and CJS across many packages?
Backend#Node.js#TypeScript#Backend
0

0 Answers

Post Your Answer

Use ``` code ``` for syntax highlighting