Sub topic 9
Shipping ESM and CommonJS together, with matching types
This chapter assumes you can write a package.json exports map with a types condition, you know what "type": "module" does, and you have a working tsc build for a library. It covers the case where one package must serve both import and require() consumers, and what has to match for TypeScript to give both of them correct types.
Decide whether you need a dual package
An ESM-only package is simpler. Every supported Node.js release can load ESM from CommonJS code through dynamic import(). Recent Node.js releases can also require() ES modules that have no top-level await. Check the Node.js versions you support before you rely on that.
Ship both formats when:
- Your consumers run older Node.js versions or toolchains that can only
require(). - Your consumers use CommonJS-only test runners or build scripts that you cannot change.
- Your package is a dependency of other libraries that still ship CommonJS.
Stay ESM-only when your consumers are modern, you want a single build, and you want to avoid the problems described below.
The core rule: one JavaScript file, one declaration file
TypeScript decides whether a .d.ts file describes ESM or CommonJS from the same rules Node.js uses for JavaScript:
| File extension | Format it is treated as |
|---|---|
| `.js`, `.d.ts` | Set by the nearest `package.json` `type` field (`module` means ESM, otherwise CommonJS) |
| `.mjs`, `.d.mts` | Always ESM |
| `.cjs`, `.d.cts` | Always CommonJS |
If a CommonJS consumer resolves your package to index.d.ts and your package.json says "type": "module", TypeScript treats those declarations as ESM. Under node16 or nodenext resolution that produces a mismatch error, because a CommonJS file cannot require() an ESM module in the type system. So each format needs its own declaration file, and the extension must agree with the JavaScript it describes.
That is why the dual-format exports map nests a types condition inside each of import and require:
{
"name": "@acme/slugify",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"files": ["dist"]
}Read the map from the outside in. Node.js and TypeScript match the import or require condition first, depending on how the consumer loads the package. Inside that block, types comes before default, because conditions are checked in object order and the first match wins. If default came first, TypeScript would stop there and never see types.
Because "type": "module" is set, .js means ESM and .d.ts means ESM. The CommonJS files use the explicit .cjs and .d.cts extensions.
Producing both builds
Plain tsc emits one module format per run, set by module. You have two practical options for two formats.
Option 1: two tsc runs
Keep the base tsconfig.json for ESM output and add a second config for CommonJS. This is the most transparent approach, but it needs care with extensions.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node10",
"outDir": "dist-cjs",
"declaration": true,
"declarationMap": true
}
}The output files are named .js and .d.ts again, which would be read as ESM under "type": "module". You then have to rename them to .cjs and .d.cts and rewrite the relative require() paths inside them. Doing that by hand is error-prone, which is why most dual packages use a bundler for the CommonJS side.
An alternative is to put a small package.json containing { "type": "commonjs" } inside the CommonJS output folder. The .js and .d.ts files in that folder are then read as CommonJS, and you point the require condition at that folder. This avoids renaming and keeps relative paths intact.
Option 2: a bundler that emits both
Tools such as tsup can emit ESM, CommonJS, and declaration files in one command, and they pick the .cjs and .d.cts extensions for you when the package has "type": "module". Chapter 14 of this tutorial covers when this is worth the extra dependency. Whichever tool you use, check the file names it writes against the exports map, because a mismatch is the most common dual-package error.
Keep the legacy fields as fallbacks
Tools that ignore exports still read main, module and types. The example above sets main to the CommonJS file because the oldest tooling uses require(). It sets module to the ESM file for bundlers that look for it, and types to the ESM declarations. Node.js ignores module, and it is a bundler convention rather than a Node.js feature. Consumers on moduleResolution: "node10" cannot read exports at all, so they only see types. For them, the .d.ts file will be treated according to your type field, which usually works because node10 does not enforce the ESM/CommonJS split.
The dual package hazard
If both builds can be loaded in one process, the same package may be loaded twice: once as ESM and once as CommonJS. Each copy has its own module state. This is the dual package hazard, and it shows up when your library holds state or when consumers use instanceof against your classes.
- A class instance created by the ESM copy fails
instanceofagainst the CommonJS copy of the same class. - A module-level cache or registry exists twice, so two parts of the application disagree.
For a pure function library like slugify, this does not matter. For libraries with state or classes, there are two common mitigations:
- Keep the state in one CommonJS file, and make the ESM entry a thin wrapper that re-exports it.
- Go ESM-only.
Type-only and runtime differences
CommonJS and ESM differ in how default and named exports appear. Prefer named exports in a dual package. A CommonJS build that uses export default produces exports.default, and a consumer who calls require("@acme/slugify") gets an object with a default property instead of the function. export = fixes the CommonJS shape but cannot be used in the ESM build. Named exports behave the same in both formats, which is why the slugify library exports a named function.
Verify the result
Run both checks from the pre-release sequence before you publish:
npm run build
npm pack --dry-run
npx publint
npx @arethetypeswrong/cli --pack .npm pack --dry-run confirms that .cjs and .d.cts files are in the tarball. publint checks that every path in exports exists and that extensions agree with type. Are the Types Wrong resolves the package under node10, node16 (as CommonJS and as ESM) and bundler, and reports problems such as a missing .d.cts or a CommonJS resolution that lands on ESM types.
Then test both module systems from a separate project that installs the packed tarball. A CommonJS consumer looks like this:
const { slugify } = require("@acme/slugify");
console.log(slugify("Hello, World!"));An ESM consumer looks like this:
import { slugify } from "@acme/slugify";
console.log(slugify("Hello, World!"));Both should print hello-world. Add a TypeScript file in each mode, with module set to nodenext, to confirm the types resolve too.
Common errors
| Symptom | Likely cause |
|---|---|
| `ERR_REQUIRE_ESM` when calling `require()` | The `require` condition points at an ESM file, or the `.cjs` file was not built |
| TypeScript error about the module being ESM when imported from CommonJS | The `require` condition resolves to a `.d.ts` file in a `"type": "module"` package |
| Types work with `import` but resolve to `any` with `require` | Missing `types` condition inside `require` |
| `instanceof` fails across consumers | Dual package hazard: two copies loaded |
| `Cannot find module` for a `.cjs` path | `files` omits it, or the build wrote different names |
Exercise
Your package has "type": "module". A CommonJS consumer using moduleResolution "nodenext" imports it and TypeScript reports that the module is ESM. Your exports map has "require": { "types": "./dist/index.d.ts", "default": "./dist/index.cjs" }. What is wrong and how do you fix it?
Show answer
The require condition points its types at index.d.ts, which TypeScript reads as ESM because of "type": "module". Emit a CommonJS declaration file named index.d.cts and set "types": "./dist/index.d.cts" under require, keeping default pointing at ./dist/index.cjs.
Exercise
Why must the "types" condition appear before "default" inside each of "import" and "require"?
Show answer
Conditions are matched in object order and the first match wins. "default" always matches, so if it comes first, TypeScript never reaches "types" and cannot find the declarations.