Sub topic 13
Publishing a Library for Both Modes
This chapter assumes you know how nodenext and bundler resolve imports, how package.json exports conditions work, and how a file's format (ESM or CommonJS) is decided. Here you apply that knowledge to one task: shipping a package that type-checks and loads correctly for every kind of consumer.
Who consumes your package
A published library is resolved by someone else's compiler, under settings you don't control. Three consumers matter in practice:
| Consumer | Typical settings | Condition it matches |
|---|---|---|
| Node.js ES module project | `module: nodenext`, file is ESM | `import` |
| Node.js CommonJS project | `module: nodenext`, file is CJS | `require` |
| Bundler-based app | `module: preserve`, `moduleResolution: bundler` | `import` (a bundler treats `import` statements as ESM) |
Your job is to make all three succeed with one package.json. The exports map is the contract. Each consumer reads it and picks a branch, and TypeScript picks both a runtime file and a declaration file from that branch.
Author the source under nodenext
Write the library with module: nodenext, even if you expect most users to use a bundler. The reason is asymmetry. Code that satisfies nodenext (explicit .js extensions on relative imports, no directory imports, no reliance on bundler-only features) also works under bundler. The reverse is not true. A library written with extensionless relative imports compiles under bundler but breaks in Node, and the emitted declaration files can break consumers that use nodenext.
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"noEmit": true
},
"include": ["src"]
}With "type": "module" in package.json, every .ts file in src is ESM, so relative imports need extensions:
// src/index.ts
export { greet } from "./greet.js";
export type { GreetOptions } from "./greet.js";// src/greet.ts
export interface GreetOptions {
excited?: boolean;
}
export function greet(name: string, options: GreetOptions = {}): string {
return `Hello, ${name}${options.excited ? "!" : "."}`;
}Here noEmit is deliberate. In this setup tsc only type-checks, and a separate build step produces the two output formats. The next section explains why.
Producing two builds
A single tsc run emits one module format. A package with "type": "module" cannot make tsc emit CommonJS from the same module: nodenext configuration, because the format of each .ts file follows the nearest package.json. You have two common options:
- Run
tsctwice with different configurations and output folders. Each folder then needs its ownpackage.jsonwith the righttypefield, and the declaration files need matching treatment. - Use a build tool that emits both formats and both kinds of declaration files in one pass.
The second option is simpler, and it produces exactly the file layout the exports map below expects. This example uses tsup, but any tool that emits .js, .cjs, .d.ts and .d.cts works:
{
"name": "example-lib",
"version": "1.0.0",
"type": "module",
"files": ["dist"],
"main": "./dist/index.cjs",
"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"
}
},
"./package.json": "./package.json"
},
"scripts": {
"typecheck": "tsc",
"build": "tsup src/index.ts --format esm,cjs --dts"
},
"devDependencies": {
"tsup": "^8.0.0",
"typescript": "^5.8.0"
}
}Three details in this file matter.
- The
typescondition comes first in each branch. TypeScript reads conditions in order and takes the first one that matches. Ifdefaultcame first, it would match beforetypeswas ever considered. - There are two declaration files, not one. The format of a
.d.tsfile follows the nearestpackage.json. Here that is"type": "module", soindex.d.tsis read as ESM. If a CommonJS consumer undernodenextwere pointed at it, TypeScript would see an ESM declaration for a module that is actually CommonJS at runtime. The.d.ctsfile is declared CommonJS, so the types match the runtime file. This mismatch is a common published-package bug. mainandtypesstay at the top level as fallbacks. Consumers using the oldernode10resolution ignoreexportsand read these fields. They get CommonJS runtime code and the ESM declaration file, which is good enough for simple packages. Note thatnode10consumers cannot see subpath exports at all.
Keep the declaration files honest
Declaration files are part of your public API, so they get resolved by the consumer's compiler. Three rules prevent most failures:
- Keep
.jsextensions on relative imports in source. They are copied into the emitted declarations, and a consumer usingnodenextneeds them. - Do not use
pathsaliases in code that you publish.tscdoes not rewrite alias specifiers in emitted JavaScript or declarations, so a consumer would see an import like@/utilsthat resolves to nothing. Use relative imports in the library. - Declare packages that appear in your public types, such as
@types/nodeor a type-only dependency, independenciesorpeerDependencies. Otherwise consumers see unresolved types inside your.d.tsfiles.
Test as each consumer
Compiling the library tells you nothing about how consumers resolve it. Install the packed tarball into a scratch project and check it under each mode. Create two configuration files and two source files in the scratch project:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"noEmit": true
},
"include": ["check.mts", "check.cts"]
}Save that as tsconfig.node.json. Save the next one as tsconfig.bundler.json:
{
"compilerOptions": {
"module": "preserve",
"moduleResolution": "bundler",
"target": "es2022",
"strict": true,
"noEmit": true
},
"include": ["check.mts"]
}The .mts file is always ESM and the .cts file is always CommonJS, so one nodenext configuration exercises both branches of your exports map:
// check.mts
import { greet } from "example-lib";
const message: string = greet("esm", { excited: true });
console.log(message);// check.cts
import { greet } from "example-lib";
const message: string = greet("cjs");
console.log(message);Then build, pack, install and check:
npm run build
npm pack --pack-destination /tmp
mkdir -p /tmp/consumer && cd /tmp/consumer
npm init -y
npm install --save-dev typescript /tmp/example-lib-1.0.0.tgz
npx tsc -p tsconfig.node.json --traceResolution | grep "example-lib"
npx tsc -p tsconfig.bundler.jsonIn the trace output for check.cts you should see index.d.cts, and for check.mts you should see index.d.ts. If both files resolve to the same declaration file, the exports map is wrong. A publishing check tool such as npx @arethetypeswrong/cli --pack . automates this comparison across resolution modes and reports mismatches between types and runtime format. Run it before every release.
Trade-offs and failure modes
The dual package hazard. If an application loads both index.js and index.cjs (for example, one dependency uses import and another uses require), it gets two separate copies of your module. Module-level state is duplicated, and instanceof checks against classes from your library fail across the boundary. Libraries that hold state or export classes should consider shipping ESM only, or have the CommonJS entry load the ESM build so only one copy exists.
ESM only is often enough. Recent Node.js versions (22.12 and later) can require() an ES module synchronously, provided it has no top-level await, and TypeScript 5.8 and later model this under nodenext. For a library that targets current Node versions, shipping a single ESM build with one types entry avoids the dual-package hazard and the second declaration file. Keep the dual build when you must support older Node versions or CommonJS consumers on older TypeScript.
Subpath exports multiply the work. Each entry such as "./utils" needs its own import and require branches and its own pair of declaration files. Generate the map from your build configuration rather than editing it by hand.
Bundlers are forgiving, so they hide bugs. A bundler consumer succeeds even when the nodenext branches are broken. Do not treat a passing bundler check as evidence that the package works in Node.
Exercise
A package has "type": "module" and an exports map whose require branch lists "types": "./dist/index.d.ts" and "default": "./dist/index.cjs". A CommonJS file under nodenext imports it. What goes wrong, and what is the fix?
Show answer
TypeScript reads index.d.ts as an ES module because of "type": "module", while the runtime file index.cjs is CommonJS. The declarations describe the wrong module format for a require consumer, which can produce errors about ES module imports from CommonJS or incorrect types for the default export. The fix is to emit a separate index.d.cts and point the require branch's "types" condition at it.
Exercise
A library author writes import { helper } from "@/utils/helper" using a paths alias, and publishes the compiled output. Why does this fail for consumers, and what should the author do?
Show answer
tsc does not rewrite paths aliases in emitted JavaScript or declaration files, so the published code contains the literal specifier "@/utils/helper", which the consumer cannot resolve. The author should use relative imports with .js extensions in the library source, or add a build step that rewrites aliases, and verify the result by installing the packed tarball in a scratch project.
Exercise
Your tsconfig.node.json check passes for check.mts but the traceResolution output for check.cts also shows index.d.ts. Which part of package.json do you inspect first, and why?
Show answer
Inspect the require branch of the exports map. A .cts file imports through the require condition, so that branch should list index.d.cts under "types". Seeing index.d.ts means the branch points at the wrong file, or the "types" condition is missing or listed after "default" so it is never reached.