Executive Summary (Quick Answer): egoist/tsup has established itself as the de facto standard for modern TypeScript library authors by combining the raw sub-50ms transpilation velocity of esbuild with an isolated TypeScript Compiler API worker that emits bundled
.d.tsand.d.ctsdeclarations. While marketed as zero-config, production repositories require explicit declarations for dual ESM and CJS export maps, Node runtime shims, and externalized peer dependencies to navigate the Node.js Dual Package Hazard. With the arrival oftsup v9.0.0, teams dropping Node versions prior to 22.18 gain access to first-class plugin typing and cleaner tsconfig resolution, cutting monorepo CI build times by over 70%.
๐ก Key Takeaways (TL;DR)
- The Library Bundling Bottleneck: Building application code with modern bundlers is solved, but packaging reusable TypeScript libraries that run across CommonJS servers, ESM bundlers, and modern runtimes requires dual compilation and bundled types, a workflow that previously demanded brittle Rollup configurations.
-
Hybrid Speed Architecture:
tsupachieves instant builds by splitting responsibilities. It offloads syntax stripping, code splitting, and minification to a Go-powered esbuild process, while dispatching type generation to an asynchronous worker runningrollup-plugin-dts. -
Configuration Traps: Even flawless build artifacts break downstream if
package.jsonexports do not map.d.tsand.d.ctscleanly. Teams must enforce strict export declarations to satisfy TypeScript NodeNext resolution. -
tsup v9.0 Migration Invariants: The
v9.0.0milestone enforces Node.js 22.18+, drops legacybaseUrlworkarounds intsconfig.json, and exposes formal plugin interfaces for custom transform pipelines. - Ecosystem Telemetry: Reposen tracks egoist/tsup with over 11,300 stars, indexing it as a primary tier build tool across production open-source ecosystems.
1. The Problem: Why Bundling TypeScript Libraries Still Hurts
Building a consumer web application with Next.js, Vite, or Remix is straightforward because the application owns the terminal runtime. The application code bundles directly into static assets or a controlled server container.
Building and distributing a reusable TypeScript library, an internal design system, or a shared monorepo SDK is fundamentally harder. Library authors face a matrix of competing consumer runtimes:
-
The Dual-Package Hazard (ESM vs. CJS): Downstream consumers run a fragmented mix of legacy CommonJS microservices and modern ECMAScript Module applications. Emitting both
.mjs(or.js) and.cjsartifacts without duplicating internal package state or corrupting global singletons requires surgical export maps. -
Declaration Generation Bottlenecks: While
tsccompiles TypeScript accurately, emitting dozens of fragmented.d.tsfiles across deep folder trees pollutes npm packages, degrades IDE autocomplete latency, and exposes private internal utility signatures. -
Rollup Boilerplate Fatigue: Historically, publishing a production dual-package required maintaining intricate Rollup pipelines comprising
@rollup/plugin-typescript,@rollup/plugin-node-resolve,@rollup/plugin-commonjs, androllup-plugin-dts. These custom configurations frequently broke during major toolchain upgrades.
2. Enter tsup: Minimalist Ergonomics, Maximum Throughput
Created by Egoist, tsup (egoist/tsup) eliminates build script maintenance by orchestrating best-in-class compiler primitives behind a declarative API.
Under the Hood: The Two-Engine Architecture
Instead of re-implementing JavaScript parsing or type checking, tsup coordinates two specialized engines:
- High-Speed Transpilation via esbuild: Written in Go, esbuild strips TypeScript type annotations, handles code splitting, and writes production bundles in tens of milliseconds. Because esbuild completely bypasses type validation, compilation time remains constant even as thousands of lines of TypeScript are added.
-
Declarative Typing via rollup-plugin-dts: Because esbuild cannot emit
.d.tsdefinitions,tsupspawns an isolated worker running the official TypeScript Compiler API. It traces the public export graph, rolls internal interfaces into a consolidated.d.tsfile, and treeshakes unused private type aliases.
{
"layout": "pipeline",
"title": "The tsup Hybrid Compilation Pipeline",
"caption": "How tsup combines esbuild for near-instant transpilation with the TypeScript compiler API and Rollup for bundled declarations.",
"steps": [
{
"kind": "input",
"badge": "SOURCE CODE",
"title": "TypeScript Library Source (src/index.ts)",
"accent": "slate"
},
{
"kind": "stage",
"badge": "ENGINE 1 ยท GO CORE",
"title": "esbuild Code Bundler & Minifier",
"subtitle": "Sub-50ms Parallel Execution",
"accent": "cyan",
"edgeLabel": "Stripped Syntax & Chunks",
"items": [
"Parses and transpiles TypeScript syntax without type checking overhead",
"Generates tree-shaken ESM (.js) and CommonJS (.cjs) bundles simultaneously"
]
},
{
"kind": "stage",
"badge": "ENGINE 2 ยท TS WORKER",
"title": "TypeScript Compiler API & rollup-plugin-dts",
"subtitle": "Isolated Type Declaration Pipeline",
"accent": "purple",
"edgeLabel": "Bundled Type Signatures",
"items": [
"Extracts public API types and collapses deep internal interfaces",
"Emits matching .d.ts and .d.cts declarations for NodeNext compatibility"
]
},
{
"kind": "stage",
"badge": "REGISTRY READY",
"title": "npm Artifact Validation & Exports Mapping",
"subtitle": "Dual Package Verification",
"accent": "emerald",
"items": [
"Validates package.json exports keys against Node.js resolution rules",
"Ensures zero runtime shim regressions and passes arethetypeswrong audits"
]
}
]
}
3. Production Configuration Blueprint
While quick command-line commands like tsup src/index.ts --dts suffice for prototyping, enterprise libraries require deterministic configuration files to guarantee reproducible releases across CI runners.
The Standard tsup.config.ts
Here is the production baseline for shipping modern dual-package TypeScript libraries:
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts"],
format: ["cjs", "esm"],
dts: true,
splitting: true,
sourcemap: true,
clean: true,
shims: true,
treeshake: true,
minify: false,
target: "es2022",
external: ["react", "react-dom"],
});
Aligning package.json Exports with Modern Standards
A perfectly executed tsup build will still fail in downstream repositories if package.json does not declare export conditions correctly. Modern module resolution engines require matching declaration extensions for ESM and CommonJS:
{
"name": "@acme/core-sdk",
"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"
}
}
Engineering Invariant: Always maintain a standalone
npm run typecheckstep in your continuous integration pipeline. Becauseesbuildstrips type annotations without validation, relying exclusively ontsup --dtscan allow syntax-valid type bugs in test files or unexported modules to slip past code review.
4. Comparing the TypeScript Library Bundler Landscape
Selecting the appropriate build tool depends on package complexity, monorepo scale, and the target runtime environment:
| Tooling Platform | Core Transpiler | Declaration Bundling | Dual ESM & CJS | Setup Complexity | Primary Sweet Spot |
|---|---|---|---|---|---|
| tsup (egoist/tsup) | esbuild (Go) | Built-in via Rollup DTS | Native & Zero-Config | Minimal (15-line config) | TypeScript libraries, CLI utilities, and monorepo packages |
| unbuild (unjs/unbuild) | Rollup & esbuild | Built-in via mkdist & rollup-dts | Native | Low | UnJS ecosystem utilities and modern ESM-first packages |
| Rollup (Bespoke) | Acorn & Babel / SWC | Manual via plugins | Manual plugin setup | High (100+ lines boilerplate) | Highly specialized bundles requiring custom AST mutations |
| Vite (Library Mode) | esbuild & Rollup | Requires vite-plugin-dts | Supported | Moderate | UI component libraries already using Vite for development |
| tsdown (Rolldown) | Rolldown (Rust) | Built-in native DTS | Native | Experimental | Next-generation unified bundler evaluating Rust toolchains |
5. Critical Gotchas & tsup v9.0 Upgrade Considerations
Teams adopting or upgrading tsup in high-velocity codebases frequently encounter four recurring architectural gotchas:
1. Breaking Changes in tsup v9.0.0
The release of tsup v9.0.0 introduces significant modernize-first requirements:
- Node.js 22.18+ Baseline: Versions of Node prior to 22.18 are formally deprecated. CI runners executing on older LTS distributions (such as Node 18 or early Node 20 releases) will fail during bundle startup.
-
Removal of Legacy
baseUrlResolution: Previous releases permitted loose relative imports whenbaseUrl: "."was set intsconfig.json.v9.0.0enforces strict standard module resolution paths. -
Formal
PluginType Export: Custom transformation extensions can now safely import thePlugininterface directly fromtsup, simplifying internal company build wrappers.
2. The .d.ts vs .d.cts Dual Packaging Trap
When "type": "module" is configured in package.json, TypeScript's NodeNext resolution demands that CommonJS require statements resolve to .d.cts definition files. If your export map references ./dist/index.d.ts under the require key, TypeScript will throw module resolution errors for CommonJS consumers. Always audit your package using the authoritative AreTheTypesWrong (attw) specification.
3. Memory Exhaustion in Large Monorepos
Because esbuild completes in under 100 milliseconds while the declaration worker initializes a complete TypeScript abstract syntax tree, large monorepos building dozens of packages in parallel can trigger Node process Out-Of-Memory errors. To optimize memory footprint:
- Use a dedicated
tsconfig.build.jsonthat explicitly excludes test suites, mock files, and documentation stories. - Pass
--tsconfig tsconfig.build.jsonto the tsup build invocation.
4. Accidental Inlining of Runtime Dependencies
By default, tsup externalizes packages declared under dependencies and peerDependencies, while bundling packages listed in devDependencies. If an engineer installs a runtime utility (such as lodash-es or date-fns) as a dev dependency, tsup will silently compile that entire library into your distribution bundle. Always ensure runtime utilities are placed in dependencies or explicitly passed to external: [...].
6. Engineering Leadership Perspective: The Business Value of Fast Tooling
From a technical leadership viewpoint, build configurations are invisible until they fail. Upgrading library maintenance infrastructure to tsup provides quantifiable organizational dividends:
-
Accelerated CI Cycles: Migrating internal design systems and core libraries from legacy Rollup or Webpack configurations to
tsuproutinely cuts compilation durations by 70% to 90%, yielding noticeable reductions in GitHub Actions compute billing. -
Lowered Cognitive Load: Standardizing on clean
tsup.config.tsdeclarations eliminates the need for dedicated tooling maintenance engineers. New developers can inspect, understand, and modify library build targets within minutes. - Deterministic Dual Publishing: Providing verified ESM and CommonJS artifacts out of the box prevents breaking downstream microservices, ensuring smooth adoption across legacy and modern application repositories alike.
Frequently Asked Questions (FAQ)
Does tsup validate TypeScript types during compilation?
No. tsup relies on esbuild for code transformation, which deliberately strips types without checking them to maximize speed. Type checking only occurs during declaration generation if dts: true is enabled. For comprehensive safety, teams must always run tsc --noEmit as an explicit step in their CI/CD pipeline.
Should I enable minification when publishing a shared library?
For public or shared libraries, you should keep minify: false. Downstream application bundlers (such as Next.js, Vite, or Webpack) already minify their final bundles. Pre-minifying library code obscures stack traces during customer debugging and can hinder downstream tree-shaking algorithms. Reserve minify: true for standalone command-line tools or self-contained browser script tags.
How does tsup handle Node.js globals like __dirname in ESM output?
When shims: true is enabled in tsup.config.ts, tsup automatically injects polyfills for CommonJS globals like __dirname, __filename, and require into the ESM output using import.meta.url. If your library targets edge runtimes like Cloudflare Workers or Vercel Edge alongside Node, split your build targets into distinct configurations to prevent injecting incompatible Node shims into edge bundles.
How do I bundle selective dependencies while keeping others external?
tsup automatically externalizes all packages listed in dependencies and peerDependencies. If you want to bundle a specific internal utility package into your output, declare it inside the noExternal: ['@acme/internal-utils'] array in your tsup.config.ts file.
Originally published on Reposen. Track live open-source releases, breaking changes, and AI radar telemetry at reposen.se.
Top comments (0)