TExcelTAD
Home › JS Packages & Bundlers: npm, Yarn, pnpm, Webpack, Rollup, esbuild › TypeScript Libraries: Types & Dual Packages

TypeScript Libraries: Types & Dual Packages

A library written in TypeScript ships JavaScript (what runs) plus declaration files (.d.ts, what editors and tsc read in the consumer's project). Bundlers produce the JavaScript well, but none of the fast ones produce declarations: that needs the TypeScript compiler, because only it understands the types. So the standard recipe splits the job:

Job Tool
type check tsc --noEmit
JavaScript, ESM + CJS a bundler: Rollup, esbuild, or tsup/tsdown (wrappers around them)
.d.ts files tsc --emitDeclarationOnly
check the published shape a consumer project that imports both formats (or the arethetypeswrong tool)

The TypeScript course covers writing declarations by hand; this lesson is about generating and shipping them.

Building the library

bash · try it yourself
mkdir -p temp/src && cd temp
cat > package.json <<'JSON'
{
  "name": "@learner/temp",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": {
      "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
      "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
    }
  },
  "main": "./dist/index.cjs",
  "types": "./dist/index.d.cts",
  "files": ["dist"],
  "scripts": {
    "typecheck": "tsc --noEmit",
    "build:js": "esbuild src/index.ts --bundle --format=esm --outfile=dist/index.js && esbuild src/index.ts --bundle --format=cjs --outfile=dist/index.cjs",
    "build:types": "tsc --emitDeclarationOnly --outDir dist && cp dist/index.d.ts dist/index.d.cts",
    "build": "npm run typecheck && npm run build:js && npm run build:types"
  }
}
JSON
npm install -D typescript@5.9.3 esbuild@0.28.2 > /dev/null 2>&1
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "strict": true,
    "declaration": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}
JSON
cat > src/index.ts <<'TS'
export type Unit = 'C' | 'F';
export interface Reading { value: number; unit: Unit }

export function convert(r: Reading, to: Unit): Reading {
  if (r.unit === to) return r;
  const value = to === 'F' ? r.value * 9 / 5 + 32 : (r.value - 32) * 5 / 9;
  return { value: Math.round(value * 10) / 10, unit: to };
}
TS
npm run -s build 2>&1 | grep -v '^$\|⚡\|dist/index'
ls dist
cat dist/index.d.ts
index.cjs
index.d.cts
index.d.ts
index.js
export type Unit = 'C' | 'F';
export interface Reading {
    value: number;
    unit: Unit;
}
export declare function convert(r: Reading, to: Unit): Reading;

Two tsconfig options make this split safe:

  • isolatedModules: true makes tsc reject code that a single-file transpiler (esbuild, SWC) can't compile correctly, such as re-exporting a type without export type.
  • verbatimModuleSyntax: true keeps import type explicit, so it's obvious which imports disappear at runtime.

The .d.cts copy exists because, with "type": "module", TypeScript reads a .d.ts file as describing an ES module. A CommonJS consumer resolving the require condition needs declarations that describe a CommonJS module, which is what the .d.cts extension says. A single declaration file for both formats is the most common cause of "the types are wrong" bug reports for dual packages.

A broken consumer, caught by the types

Publish it, then use it from a TypeScript project with a mistake in it:

bash · try it yourself
mkdir -p temp/src && cd temp
cat > package.json <<'JSON'
{ "name": "@learner/temp", "version": "1.0.0", "type": "module",
  "exports": { ".": { "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
                      "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } } },
  "main": "./dist/index.cjs", "types": "./dist/index.d.cts", "files": ["dist"] }
JSON
npm install -D typescript@5.9.3 esbuild@0.28.2 > /dev/null 2>&1
echo '{ "compilerOptions": { "target": "es2022", "module": "nodenext", "strict": true, "declaration": true, "isolatedModules": true, "skipLibCheck": true }, "include": ["src"] }' > tsconfig.json
printf "export type Unit = 'C' | 'F';\nexport const toF = (c: number): number => c * 9 / 5 + 32;\n" > src/index.ts
npx esbuild src/index.ts --format=esm --outfile=dist/index.js --log-level=warning
npx esbuild src/index.ts --format=cjs --outfile=dist/index.cjs --log-level=warning
npx tsc --emitDeclarationOnly --outDir dist && cp dist/index.d.ts dist/index.d.cts
npm publish > /dev/null 2>&1
mkdir ../weather && cd ../weather
npm init -y > /dev/null && npm pkg set type=module
npm install @learner/temp > /dev/null && npm install -D typescript@5.9.3 > /dev/null 2>&1
echo '{ "compilerOptions": { "module": "nodenext", "strict": true, "noEmit": true } }' > tsconfig.json
cat > app.ts <<'TS'
import { toF, type Unit } from '@learner/temp';
const u: Unit = 'K';
console.log(toF('20'));
TS
cat > legacy.cts <<'TS'
import temp = require('@learner/temp');
console.log(temp.toF(100));
TS
npx tsc; echo "tsc exit code: $?"
sed -i "s/'K'/'C'/; s/'20'/20/" app.ts
npx tsc && echo "types OK for both the import and the require condition"
app.ts(2,7): error TS2322: Type '"K"' is not assignable to type 'Unit'.
app.ts(3,17): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
tsc exit code: 2
types OK for both the import and the require condition

Both mistakes ('K' isn't a Unit, a string isn't a number) were caught in the consumer's project, from declarations that tsc generated in the library's build. legacy.cts is a CommonJS TypeScript file, so its import resolved through the require condition to index.d.cts.

Order matters inside exports

Conditions are tried in order, and the first match wins. Put types first in each branch (or, as here, nest it per format), and default last:

json
"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"
}

Top-level main and types are fallbacks for old tools that don't read exports.

Shortcuts: tsup, tsdown, unbuild

Writing the split by hand teaches you what's going on; in practice many libraries use a wrapper that does the same with one config:

Tool Built on Notes
tsup esbuild (+ Rollup for .d.ts bundling) tsup src/index.ts --format esm,cjs --dts
tsdown Rolldown tsup's successor, from the Vite/Rolldown team
unbuild Rollup used across the Nuxt/UnJS ecosystem
Vite library mode Rollup/Rolldown see the Vite course

They aren't in this course's offline registry, so they're not demonstrated here; the Mini Project builds a library the explicit way, with tsc and Rollup.

Test yourself

Why can't esbuild produce .d.ts files?

  1. It's not allowed by Microsoft
  2. It strips types without understanding them; only the TypeScript compiler knows the types
  3. It can, with --dts
  4. Declarations are only for JavaScript

In a package with "type": "module", why ship index.d.cts for the require condition?

  1. It's smaller
  2. A .d.ts there is read as describing an ES module; .d.cts describes a CommonJS module
  3. TypeScript requires both
  4. For source maps

What does isolatedModules: true protect against?

  1. Slow builds
  2. Code that a single-file transpiler like esbuild can't compile correctly
  3. Circular imports
  4. Missing tests