Sub topic 14
When to use tsup or a declaration bundler instead of plain tsc
This chapter assumes you have followed the earlier chapters. You can configure tsc to emit JavaScript and .d.ts files, you know how the exports field maps conditions to files, and you understand why a dual ESM and CommonJS package needs separate declaration files (.d.ts and .d.cts). The question here is when tsc alone stops being enough, and what to reach for when it does.
What plain tsc gives you
The setup from the earlier chapters uses only the TypeScript compiler. tsc reads src, writes one .js file and one .d.ts file per source file into dist, and optionally writes .js.map and .d.ts.map files. For many libraries that is the right answer, because:
- The output mirrors the source tree, so subpath exports such as
./localemap directly onto folders. - Declaration maps work. "Go to definition" in a consumer's editor jumps to your
.tssource, as long as the source is published or reachable. - There is one tool and one configuration file. Failures are TypeScript errors, not plugin errors.
- Consumers' bundlers can tree-shake per file, because your modules are still separate files.
If your package is ESM-only, has a handful of entry points, and uses relative imports with .js extensions, keep using tsc. Adding a bundler to that project adds a dependency and a second configuration without fixing a problem you have.
Problems that plain tsc does not solve
tsc is a compiler, not a packager. It transforms each file and leaves the import graph alone. These are the situations where that becomes a cost.
| Situation | Why tsc struggles | What a bundler does |
|---|---|---|
| Dual ESM and CommonJS output | One `tsc` run emits one module format, set by `module` and the nearest `type` field. Two formats need two runs, two `outDir` values, and a way to give the CommonJS output a `.cjs` extension. | Emits both formats from one command, with `.js`/`.cjs` and `.d.ts`/`.d.cts` names. |
| Extensionless or aliased imports | `tsc` does not rewrite import specifiers. `import "./util"` or a `paths` alias is emitted unchanged, and Node fails at runtime. | Resolves the specifier while bundling, so the output has no unresolved imports. |
| Many internal files | A library with hundreds of small modules ships hundreds of files. This is harmless for Node but slower to install and load in some environments. | Produces one or a few output files per entry point. |
| Internal types leaking | Every exported type in any file appears in a `.d.ts` file that consumers could import by deep path, if `exports` allows it. | A declaration bundler produces one `.d.ts` per entry and drops declarations that the entry point does not reach. |
| Non-TypeScript assets | `tsc` does not handle CSS, JSON transforms, or code injected at build time. | Plugins handle these. |
The first row is the most common reason. The dual package layout from the previous chapter is possible with two tsc invocations, but you must manage two tsconfig files and rename extensions yourself. A bundler makes it a single setting.
Two kinds of tool
There are two separate jobs, and tools combine them differently.
- JavaScript bundling. Tools such as esbuild, Rollup and Rolldown combine modules and emit the format you ask for. They strip types without checking them.
- Declaration bundling. Tools such as
rollup-plugin-dts, API Extractor anddts-bundle-generatortake the declarations that TypeScript produced and merge them into one.d.tsfile per entry point.
tsup wraps both. It uses esbuild for the JavaScript and, when you enable dts, it generates declarations with the TypeScript compiler and merges them with rollup-plugin-dts. It reads your tsconfig.json for compiler options, so your strict and target settings still apply to the declaration step.
Check the maintenance status of any build tool before you adopt it. At the time of writing, the tsup project recommends tsdown, a Rolldown-based tool with a similar configuration, for new projects. The ideas in this chapter apply to both, and the option names are close.
A tsup configuration
Install the tool as a development dependency:
npm install --save-dev tsup typescriptThen create a tsup.config.ts next to package.json:
// tsup.config.ts
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
dts: true,
sourcemap: true,
clean: true,
});Each option does one job:
entrylists the files that become public entry points. For subpath exports, add one entry per subpath, for example["src/index.ts", "src/locale/index.ts"].formatselects the module formats. With"type": "module"inpackage.json, tsup writesindex.jsfor ESM andindex.cjsfor CommonJS.dtsturns on declaration output. With both formats and"type": "module", you getindex.d.tsandindex.d.cts.cleanemptiesdistbefore each build, so deleted files do not linger and get published.
The package.json matches the dual layout from the previous chapter. The file names in the map must match what the tool writes, so check dist after the first build.
{
"name": "@acme/slugify",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"files": ["dist"],
"scripts": {
"build": "tsup",
"typecheck": "tsc --noEmit",
"prepublishOnly": "npm run typecheck && npm run build"
}
}The typecheck script matters. esbuild removes types without checking them, so a build can succeed with type errors in the JavaScript path. The declaration step does check the entry graph, but running tsc --noEmit covers every file in include, including tests and files no entry point reaches. Keep your tsconfig from the earlier chapters, and either leave outDir in place (it is ignored by --noEmit) or add a separate tsconfig.build.json.
Choosing between the options
Weigh the trade-offs when you decide:
- Simplicity.
tschas the fewest moving parts. Every added tool is one more thing that can break on a TypeScript upgrade. - Correctness of types. A declaration bundler re-parses and rewrites
.d.tsfiles. Rare TypeScript features, such as somedeclare globalpatterns or complex module augmentation, can come out wrong. Always verify the bundled output with Are the Types Wrong, as shown in the verification chapter. - Debugging. Declaration maps point from a
.d.tsfile to the matching.tsfile. A bundled.d.tsmerges many sources, so editor navigation in consumers is less precise. - Reversibility. Switching from
tscto a bundler later changes file layout, which can break consumers who deep-import files. If yourexportsmap hides internals, as in the subpath chapter, the switch is safe.
Gotchas when you bundle
Dependencies must stay external
A library bundle should not contain its own dependencies. tsup treats everything in dependencies and peerDependencies as external by default, so the output still contains import "left-pad" and the consumer's package manager supplies it. Bundling a dependency into your output duplicates it and defeats version sharing. Use noExternal only for packages you deliberately inline.
Types follow the same rule. If a public type refers to a type from a dependency, that dependency, or its @types package, must be listed in dependencies or peerDependencies, as the earlier chapter on type dependencies explained. A bundler does not add it for you.
The dual package hazard gets worse
When ESM and CommonJS builds are separate bundles, each contains its own copy of any module-level state. A class defined in both bundles produces two distinct classes, and instanceof fails when a consumer loads both formats through different dependencies. If your library keeps state or exports classes that users check with instanceof, consider shipping ESM only, or make the CommonJS file a thin wrapper that loads the ESM build.
Declaration maps and source maps
sourcemap: true produces .js.map files that map bundled output back to your source files. Publish the src folder, or set the sources content to be embedded, if you want those maps to be useful to consumers. Otherwise the maps point at files that do not exist in the installed package. The dts step does not emit declaration maps in the same way as tsc, so do not expect jump-to-source from the bundled .d.ts.
Always rebuild from clean
Stale files are the usual cause of "works locally, broken after publish". Keep clean: true, then run npm pack --dry-run and read the file list every time you change the build tool or its settings.
Adding API Extractor
If you need an API report, release tags such as @internal, or one rolled-up .d.ts that strips internal declarations with documented rules, API Extractor is more thorough than the merge that tsup performs. The usual workflow is to build with tsc, point API Extractor at the main .d.ts, and let it write the rollup. It is more configuration than most libraries need. Use it when the public surface is large, several teams depend on it, and you want a failing check when the API changes by accident.
Verify the result
Whichever tool you choose, the checks from the verification chapter still apply, because they test the package a consumer receives and not your build tool.
npm run build
npm pack --dry-run
npx publint
npx @arethetypeswrong/cli --pack .Read the npm pack output first. Confirm that both .d.ts and .d.cts files are present when you ship two formats, and that every path in exports appears in the list.
Exercise
A library is ESM-only, has one entry point, and uses relative imports with .js extensions. A teammate proposes adding tsup. Name two reasons to say no, and one change to the project that would make tsup worthwhile.
Show answer
Reasons to say no: plain tsc already produces correct JavaScript, .d.ts files and declaration maps with one configuration file, and adding tsup adds a dependency and a second build path that can drift from the tsconfig used for type checking. Also, tsup would remove declaration maps from the type output and merge files that tsc keeps separate, which makes consumer navigation worse. A change that would justify tsup: a requirement to ship a CommonJS build alongside ESM, since one tsup command emits both formats with matching .d.ts and .d.cts files. Path aliases or extensionless imports that tsc will not rewrite are another valid answer.
Exercise
After switching to tsup with format ["esm", "cjs"] and dts: true, npm pack --dry-run lists dist/index.js, dist/index.cjs and dist/index.d.ts, but the require condition in exports points to ./dist/index.d.cts. What happens for a consumer using moduleResolution node16 with require, and how do you fix it?
Show answer
TypeScript follows the require condition to ./dist/index.d.cts, which does not exist in the published package, so the consumer gets a "could not find a declaration file" error and the module is typed as any or fails to compile under strict settings. Are the Types Wrong would report the missing file. Fix it by checking the tool's actual output names in dist and making the exports map match them, for example by setting "type": "module" so tsup writes .d.cts for the CommonJS format, then rebuilding with clean enabled and repeating npm pack --dry-run.