Sub topic 14
Publishing a Typed Package with types and exports
This chapter assumes you can run tsc, edit tsconfig.json, and read a package.json. It also assumes you know what declaration: true produces and how module and moduleResolution are set to nodenext. Here you will connect those pieces. You will build a library, then describe it in package.json so TypeScript finds the right .d.ts file for every consumer.
What publishing types involves
A published package has two audiences. Node.js reads the JavaScript files. TypeScript reads the declaration files. Each reader needs its own pointer from package.json to the right file, and the two pointers must agree. If they point at different builds, the types describe code that never runs.
Three parts have to line up:
- The build emits JavaScript and
.d.tsfiles into a folder such asdist. package.jsonmaps the package name to those files.- The published tarball contains the files that the map refers to.
Step 1: Emit declarations from the library
Start with a tsconfig.json for the library. It differs from an application config in a few settings.
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}rootDir makes src/index.ts compile to dist/index.js. Without it, the output folder layout depends on which files TypeScript finds, and dist/src/index.js is a common surprise. declarationMap writes .d.ts.map files, so an editor can jump from a consumer's call straight to your .ts source.
Now write the source and look at what tsc produces.
// src/index.ts
export function add(a: number, b: number): number {
return a + b;
}
// dist/index.d.ts (generated by tsc with declaration: true)
export declare function add(a: number, b: number): number;The .d.ts file keeps the signature and drops the body. When a function has no return type annotation, tsc writes the inferred type into the declaration. Annotating the public API explicitly keeps the emitted types stable and readable.
Step 2: Point package.json at the output
The exports field is the modern entry map. It lists which paths a consumer may import and which file serves each one.
{
"name": "my-lib",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"files": ["dist"]
}Each field has a job:
| Field | Read by | Purpose |
|---|---|---|
| `exports` | Node.js, bundlers, and TypeScript with `node16`, `nodenext`, or `bundler` resolution | Maps import paths to files and hides everything else |
| `types` | TypeScript with older `node10` resolution | Top-level pointer to the declaration entry |
| `main` | Older Node.js versions and tools | Top-level pointer to the JavaScript entry |
| `files` | npm when packing | Lists what goes into the tarball |
Keeping main and types next to exports costs two lines. It keeps the package usable from tools that predate exports.
How conditions are matched
Keys such as types and default inside exports are called conditions. The resolver walks the object in written order and takes the first condition it recognizes. This has one consequence you must remember: types has to come before default. A resolver that checks default first would match it for TypeScript too and load the .js file, which has no types.
TypeScript always counts types as a matching condition. It also matches import or require depending on the importing file's format, and default as the fallback.
Wait: the diagram must be in the correct fence. Here it is.
Step 3: Dual packages for ESM and CommonJS
If you need to serve both import and require consumers, each format needs its own declaration file. The reason is that TypeScript reads a .d.ts file as ESM or CommonJS according to the nearest package.json type field and the file extension. One .d.ts file cannot describe both.
{
"name": "my-lib",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
}
}
},
"files": ["dist"]
}The types condition appears first inside each branch. Because the package sets "type": "module", the .js and .d.ts files under dist/esm count as ESM. The CommonJS build needs the .cjs and .d.cts extensions to be read as CommonJS. This means two compiler runs with different settings, or a bundler that writes both formats. If you do not need CommonJS consumers, publish ESM only. It removes a whole class of mismatches.
Subpath exports
You can expose more than one entry point by adding keys that start with ./.
{
"name": "my-lib",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./testing": {
"types": "./dist/testing.d.ts",
"default": "./dist/testing.js"
}
},
"files": ["dist"]
}Consumers then write import { mockClock } from "my-lib/testing". Anything not listed is private. A deep import such as my-lib/dist/internal.js fails in Node.js and in TypeScript with a resolution error. That is the main benefit of exports, and it is also the main cause of breakage when you add exports to an existing package. A change that adds exports can be a breaking change for anyone who imported deep paths.
Under node10 resolution, subpaths ignore exports. The typesVersions field can redirect them, but most new packages skip this and require a modern resolution mode.
Step 4: Check what consumers will see
Do not trust the config by reading it. Pack the package and install the tarball in a separate test project.
npm run build
npm pack --dry-run
npm pack--dry-run prints the files that would be published. Check that dist/index.d.ts is in the list. Then create a consumer project, install the tarball, and compile a file that imports it.
// consumer/src/check.ts
import { add } from "my-lib";
const total: number = add(1, 2);
console.log(total);Compile the consumer with module and moduleResolution set to nodenext. If the import resolves and total is a number, the entry point works. Also test with moduleResolution: "node10" if you promise support for it. Two community tools automate these checks. publint lints package.json for mistakes such as a wrong condition order. @arethetypeswrong/cli reports, for each resolution mode, whether types resolve and whether the format matches.
Common errors
- Types missing from the tarball.
fileslistsdist, but you rannpm packbefore building, or.npmignoreexcludes*.d.ts. Check with--dry-run. typesafterdefault. The consumer gets implicitanyor a "could not find a declaration file" error even though the file exists.- Wrong format for the declaration file. A CommonJS consumer resolves an ESM
.d.tsand sees an error about a module that cannot be imported withrequire. Add the.d.ctsbranch or drop CommonJS support. - Relative imports without extensions in source. Under
nodenext,import "./util"fails in your own build. Write./util.js, which TypeScript maps toutil.ts. - Public types depend on a dev dependency. If an exported signature mentions a type from
@types/nodeor another types package, move that package todependencies. Otherwise consumers seeanywhere your types should be. - Declarations that reference unexported types. With
declaration: true,tscreports an error when an exported function returns a type it cannot name. Export that type or annotate the return type.
Recap of decisions
| Question | Choice |
|---|---|
| ESM only or dual? | ESM only unless you have CommonJS consumers you cannot move |
| Keep `types` and `main` at top level? | Yes, as a cheap fallback for older tools |
| Where does `types` go in a condition object? | First |
| How to verify? | `npm pack`, install the tarball, compile a consumer, run `publint` and `attw` |
Exercise
A package sets "exports": { ".": { "default": "./dist/index.js", "types": "./dist/index.d.ts" } }. A TypeScript project using moduleResolution nodenext imports it and reports that it could not find a declaration file, even though dist/index.d.ts exists in the tarball. What is wrong, and how do you fix it?
Show answer
The resolver takes the first matching condition in written order. Because default is listed before types, it matches default and loads dist/index.js, which has no declarations. Move types before default so the entry is { "types": "./dist/index.d.ts", "default": "./dist/index.js" }.
Exercise
You add an exports field that lists only "." to a published library, and users who wrote import x from "my-lib/dist/helpers.js" now get errors. Why, and what are two ways to handle it?
Show answer
Once exports exists, only the listed paths can be imported, so the deep path is blocked. You can either release the change as a new major version, or add the deep path as an explicit subpath entry (for example "./dist/helpers.js" with its types and default conditions) to keep it working.