Generate Declaration Files for TypeScript Libraries
Intermediate12 min
Configure TypeScript to generate .d.ts declaration files and declaration maps for publishable libraries with proper package.json exports.
Prerequisites
- -TypeScript project structured as a library
- -Understanding of package.json exports
Steps
1
Configure tsconfig for declaration output
Enable declaration and declarationMap in compilerOptions.
$ cat > tsconfig.build.json << 'EOF'
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"declarationDir": "./dist/types",
"outDir": "./dist",
"noEmit": false,
"emitDeclarationOnly": true
},
"include": ["src"],
"exclude": ["src/**/*.test.ts", "src/**/*.spec.ts"]
}
EOF
Use emitDeclarationOnly: true when a bundler handles the JavaScript output. TypeScript only generates .d.ts files.
2
Generate declaration files
Run the TypeScript compiler with the build config to produce .d.ts files.
$ npx tsc --project tsconfig.build.json
3
Configure package.json exports and types
Set the types, main, and exports fields so consumers find your type declarations.
$ npm pkg set types='./dist/types/index.d.ts' main='./dist/index.js' module='./dist/index.mjs'
Use the exports field for conditional exports: types for .d.ts, import for ESM, require for CJS.
4
Verify declarations are correct
Check that the generated .d.ts files export the expected types.
$ ls -la dist/types/ && head -20 dist/types/index.d.ts
5
Test the package locally before publishing
Use npm pack to create a tarball and install it in a test project.
$ npm pack --dry-run && npm pack && echo 'Install in another project: npm install ./your-package-1.0.0.tgz'
Full Script
FAQ
Discussion
Loading comments...