When Libraries Need Declaration Files Only
You'll learn: Why some libraries only publish .d.ts files even though they're built using modern bundlers and transpilers.
The Core Scenario
Sometimes your library's JavaScript output is already handled by your build tool (like esbuild, Rollup, or Webpack), which strips types and produces optimized code fast. But there's a problem: bundlers don't generate .d.ts files. TypeScript consumers of your library need those declaration files to get type-checking and autocomplete.
This creates a split-responsibility workflow:
- Bundler: Handles transpilation → JavaScript output
- TypeScript compiler (
tsc): Handles type extraction →.d.tsoutput
Why This Happens
Modern bundlers prioritize speed. They:
- Transform TypeScript syntax to JavaScript
- Tree-shake and optimize
- Handle module formats
But they don't analyze types deeply enough to generate declaration files. That's still TypeScript's job.
The Solution Pattern
You configure tsc to only emit declarations using emitDeclarationOnly: true, while your bundler handles the actual code:
// tsconfig.json
{
"compilerOptions": {
"emitDeclarationOnly": true,
"declaration": true,
"outDir": "./dist/types"
}
}
Your build script runs both:
- Bundler creates
dist/index.js(fast transpilation) - tsc creates
dist/types/index.d.ts(type definitions)
Real-World Example
Think of a React component library built with Vite:
- Vite bundles your components into optimized JavaScript in milliseconds
- But Vite can't tell consumers what props your
<Button>component accepts - You run
tsc --emitDeclarationOnlyto generate those prop types as.d.tsfiles - Both outputs ship together in your npm package
Key Takeaway: When using fast build tools that strip types, you still need tsc to generate declaration files — but you can skip its slower transpilation step with emitDeclarationOnly.