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-nodeworks 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/exportworks with browsers and bundlers without transpiling. - Better static analysis; circular‑dependency errors are caught earlier.
- Allows mixed‑type imports (
import pkg from 'pkg'vsrequire).
Pain points we hit
- Dual package.json entries (
exportsfield) to support both consumers. - Need a build step that emits both
.cjsand.mjsfiles, 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
- In a monorepo, is it worth maintaining two output formats, or should we enforce a single module system and migrate everything at once?
- 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?
0 Answers
Post Your Answer
Use ``` code ``` for syntax highlighting