Building and publishing
Overview
So far, every project in this course ran TypeScript directly — Node or Vitest stripped the types and no build step was needed. That’s ideal for applications and scripts. But when you publish a library for others, or deploy to an environment that only runs JavaScript, you compile TypeScript into JavaScript files, and ship declaration files so users of your package get types too.
When do you need a build?
| Project | Build? |
|---|---|
Node app or script, run with node src/app.ts |
no — check with tsc --noEmit |
| Front-end app (React, Vue…) | the bundler (Vite) builds it; tsc only checks |
| Library published to npm | yes — ship .js and .d.ts |
Code for an older runtime, or serverless platforms that only accept .js |
yes |
Compiling with tsc
Turn off noEmit and tell tsc where things go:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"rewriteRelativeImportExtensions": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"isolatedDeclarations": true,
"skipLibCheck": true
},
"include": ["src"]
}npx tscdist/format.d.ts dist/format.d.ts.map dist/format.js dist/format.js.map
dist/index.d.ts dist/index.d.ts.map dist/index.js dist/index.js.maprootDir/outDir—src/index.tsbecomesdist/index.js. (SetrootDirexplicitly: since TypeScript 6 it defaults to the tsconfig’s folder, which would producedist/src/….)target— pick the oldest runtime your users have. Libraries often choose something slightly older than the latest (es2022) to be safe;tscrewrites newer syntax but never adds polyfills.declaration— the.d.tsfiles: your exported types, without implementations.declarationMap/sourceMap— let editors jump to your.tssource and debuggers show it.rewriteRelativeImportExtensions— you writeimport … from "./format.ts"(so the source also runs directly in Node); the output says"./format.js".
The output for index.ts:
export { formatMoney } from "./format.js";
export function slugify(text) {
return text.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}
//# sourceMappingURL=index.js.mapThe export type line is gone, and the import extension has been rewritten.
isolatedDeclarations
With isolatedDeclarations, TypeScript requires every exported function and variable to have explicit types where inference would need other files (return types on exported functions, for example). That makes your public API explicit, and lets faster tools generate .d.ts files file-by-file without the type checker. It’s a good habit for libraries.
package.json for a typed package
{
"name": "tiny-format",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"],
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build"
}
}exportsis the package’s public entry points. Node usesdefaultto find the code; TypeScript usestypesto find the declarations. Puttypesfirst — conditions are matched in order.- Subpath entries expose more modules:
"./parse": { "types": "./dist/parse.d.ts", "default": "./dist/parse.js" }. Anything not listed can’t be imported — which keeps internals private. fileslimits what gets published todist/(plus package.json, README and LICENSE, which npm always includes). Check withnpm pack --dry-run.prepublishOnlyguarantees a fresh build beforenpm publish.
Check your package before publishing with tools like publint and Are the Types Wrong? (npx @arethetypeswrong/cli --pack), which catch broken exports maps and type resolution problems for different consumers.
Supporting CommonJS consumers
Pure ES module packages work for Node 20+ and every bundler — and since Node 22, CommonJS code can require() ES modules too. If you still need to ship a separate CommonJS build, tools like tsdown, tsup or unbuild produce dual builds and matching declaration files from one config.
Bundlers for applications
For applications, a bundler typically does the build:
- Vite (front-end apps) — strips types with a fast transformer, bundles, minifies.
tsc --noEmitruns separately to check types. - esbuild / Rolldown — fast bundling for Node services or CLIs into a single file.
Bundlers don’t type-check. In every setup, the pattern is the same: a fast tool transforms, tsc checks.
Monorepos and project references
Large codebases split into several packages can use project references ("references": [{ "path": "../shared" }] with composite: true) and build them in dependency order with tsc --build. TypeScript 7 builds referenced projects in parallel (tunable with the experimental --builders flag).
Remember: apps can run TypeScript directly; libraries ship
.js+.d.ts. SetrootDir,outDiranddeclaration, write.tsimports withrewriteRelativeImportExtensions, and describe your entry points with anexportsmap.
Package a small library
Turn the two source files in the starter into a publishable package called tiny-format. Write its tsconfig.json (emit to dist/ from src/, with declarations, declaration maps and source maps, module: nodenext, and rewriteRelativeImportExtensions so the .ts imports work after compiling) and its package.json (type: module, an exports map with types and default conditions pointing into dist/, files: ["dist"], and build/prepublishOnly scripts). Run npm run build and check that dist/ contains .js, .d.ts and .map files, then npm pack --dry-run to see what would be published. Finally import the package in another project and check that types and autocompletion work.
// ---- src/format.ts ----
export type Currency = "USD" | "EUR" | "INR";
export function formatMoney(amount: number, currency: Currency): string {
return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount);
}
// ---- src/index.ts ----
export { formatMoney } from "./format.ts";
export type { Currency } from "./format.ts";
export function slugify(text: string): string {
return text.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}
// ---- tsconfig.json ----
// ---- package.json ----// ---- tsconfig.json ----
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"rewriteRelativeImportExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"isolatedDeclarations": true,
"skipLibCheck": true
},
"include": ["src"]
}
// ---- package.json ----
{
"name": "tiny-format",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"],
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build"
},
"devDependencies": {
"typescript": "^7.0.2"
}
}
// ---- In a project that uses it (consumer/main.ts) ----
import { formatMoney, slugify, type Currency } from "tiny-format";
const currency: Currency = "INR";
console.log(formatMoney(1250.5, currency), slugify(" Hello World! ")); // ₹1,250.50 hello-worldSummary
- Apps that Node or a bundler runs often need no build; libraries ship compiled JavaScript plus
.d.tsfiles. tscwithoutDir,rootDir,declarationandsourceMapwrites.js,.d.tsand.mapfiles.rewriteRelativeImportExtensionsturns./util.tsimports into./util.jsin the output.- The package.json
exportsmap tells Node and TypeScript where the code and the types are;filescontrols what’s published. isolatedDeclarationskeeps exported types explicit, so declaration files can be generated quickly by any tool.