# Deep Dive into tsup: Zero-Config TypeScript Bundling, Dual ESM/CJS Output, and v9.0 Gotchas

> Master egoist/tsup for bundling TypeScript libraries: esbuild speed, dual ESM/CJS outputs, .d.ts bundling, tsup v9.0 migration gotchas, and package.json exports.

- **Canonical URL**: https://reposen.se/blog/tsup-zero-config-typescript-bundling-production-guide
- **Raw Markdown URL**: https://reposen.se/blog/tsup-zero-config-typescript-bundling-production-guide/llm.txt
- **Author**: Reposen Editorial Engine
- **Published At**: 2026-11-19
- **Reading Time**: 8 min
- **Keywords**: tsup, egoist/tsup, TypeScript Library Bundling, Dual Package Hazard, esbuild Bundler, Rollup DTS, Reposen Engineering Blog

---

> **Executive Summary (Quick Answer):** [egoist/tsup](https://reposen.se/repo/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](https://esbuild.github.io/api/#bundle) with an isolated TypeScript Compiler API worker that emits bundled `.d.ts` and `.d.cts` declarations. 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](https://nodejs.org/api/packages.html#packages_dual_package_hazard). With the arrival of `tsup 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:** `tsup` achieves 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 running `rollup-plugin-dts`.
* **Configuration Traps:** Even flawless build artifacts break downstream if `package.json` exports do not map `.d.ts` and `.d.cts` cleanly. Teams must enforce strict export declarations to satisfy [TypeScript NodeNext resolution](https://www.typescriptlang.org/docs/handbook/modules/reference.html#packagejson-exports).
* **tsup v9.0 Migration Invariants:** The `v9.0.0` milestone enforces Node.js 22.18+, drops legacy `baseUrl` workarounds in `tsconfig.json`, and exposes formal plugin interfaces for custom transform pipelines.
* **Ecosystem Telemetry:** Reposen tracks [egoist/tsup](https://reposen.se/repo/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:

1. **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 `.cjs` artifacts without duplicating internal package state or corrupting global singletons requires surgical export maps.
2. **Declaration Generation Bottlenecks:** While `tsc` compiles TypeScript accurately, emitting dozens of fragmented `.d.ts` files across deep folder trees pollutes npm packages, degrades IDE autocomplete latency, and exposes private internal utility signatures.
3. **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`, and `rollup-plugin-dts`. These custom configurations frequently broke during major toolchain upgrades.

---

## 2. Enter tsup: Minimalist Ergonomics, Maximum Throughput

Created by Egoist, **[tsup (egoist/tsup)](https://reposen.se/repo/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](https://esbuild.github.io/api/#bundle) 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.ts` definitions, `tsup` spawns an isolated worker running the official TypeScript Compiler API. It traces the public export graph, rolls internal interfaces into a consolidated `.d.ts` file, and treeshakes unused private type aliases.

```diagram
{
  "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:

```typescript
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:

```json
{
  "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 typecheck` step in your continuous integration pipeline. Because `esbuild` strips type annotations without validation, relying exclusively on `tsup --dts` can 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 `baseUrl` Resolution:** Previous releases permitted loose relative imports when `baseUrl: "."` was set in `tsconfig.json`. `v9.0.0` enforces strict standard module resolution paths.
* **Formal `Plugin` Type Export:** Custom transformation extensions can now safely import the `Plugin` interface directly from `tsup`, 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)](https://github.com/arethetypeswrong/arethetypeswrong.github.io) 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.json` that explicitly excludes test suites, mock files, and documentation stories.
* Pass `--tsconfig tsconfig.build.json` to 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 `tsup` routinely cuts compilation durations by 70% to 90%, yielding noticeable reductions in GitHub Actions compute billing.
* **Lowered Cognitive Load:** Standardizing on clean `tsup.config.ts` declarations 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.
