tsdown

作者: sanity-io

使用 Rolldown 以極快速度打包 TypeScript 和 JavaScript 函式庫。在建立函式庫、產生型別宣告、打包用於…時使用。

npx skills add https://github.com/sanity-io/next-sanity --skill tsdown

tsdown - The Elegant Library Bundler

Blazing-fast bundler for TypeScript/JavaScript libraries powered by Rolldown and Oxc.

When to Use

  • Building TypeScript/JavaScript libraries for npm
  • Generating TypeScript declaration files (.d.ts)
  • Bundling for multiple formats (ESM, CJS, IIFE, UMD)
  • Optimizing bundles with tree shaking and minification
  • Migrating from tsup with minimal changes
  • Building React, Vue, Solid, or Svelte component libraries

Quick Start

# Install
pnpm add -D tsdown

# Basic usage
npx tsdown

# With config file
npx tsdown --config tsdown.config.ts

# Watch mode
npx tsdown --watch

# Migrate from tsup
npx tsdown-migrate

Basic Configuration

import {defineConfig} from 'tsdown'

export default defineConfig({
  entry: ['./src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  clean: true,
})

Core References

TopicDescriptionReference
Getting StartedInstallation, first bundle, CLI basicsguide-getting-started
Configuration FileConfig file formats, multiple configs, workspaceoption-config-file
CLI ReferenceAll CLI commands and optionsreference-cli
Migrate from tsupMigration guide and compatibility notesguide-migrate-from-tsup
PluginsRolldown, Rollup, Unplugin supportadvanced-plugins
HooksLifecycle hooks for custom logicadvanced-hooks
Programmatic APIBuild from Node.js scriptsadvanced-programmatic
Rolldown OptionsPass options directly to Rolldownadvanced-rolldown-options
CI EnvironmentCI detection, 'ci-only' / 'local-only' valuesadvanced-ci

Build Options

OptionUsageReference
Entry pointsentry: ['src/*.ts', '!**/*.test.ts']option-entry
Output formatsformat: ['esm', 'cjs', 'iife', 'umd']option-output-format
Output directoryoutDir: 'dist', outExtensionsoption-output-directory
Type declarationsdts: true, dts: { sourcemap, compilerOptions, vue }option-dts
Target environmenttarget: 'es2020', target: 'esnext'option-target
Platformplatform: 'node', platform: 'browser'option-platform
Tree shakingtreeshake: true, custom optionsoption-tree-shaking
Minificationminify: true, minify: 'dce-only'option-minification
Source mapssourcemap: true, 'inline', 'hidden'option-sourcemap
Watch modewatch: true, watch optionsoption-watch-mode
Cleaningclean: true, clean patternsoption-cleaning
Log levellogLevel: 'silent', failOnWarn: falseoption-log-level

Dependency Handling

FeatureUsageReference
Never bundledeps: { neverBundle: ['react', /^@myorg\//] }option-dependencies
Always bundledeps: { alwaysBundle: ['dep-to-bundle'] }option-dependencies
Only bundledeps: { onlyBundle: ['cac', 'bumpp'] } - Whitelistoption-dependencies
Skip node_modulesdeps: { skipNodeModulesBundle: true }option-dependencies
Auto externalAutomatic peer/dependency externalizationoption-dependencies

Output Enhancement

FeatureUsageReference
Shimsshims: true - Add ESM/CJS compatibilityoption-shims
CJS defaultcjsDefault: true (default) / falseoption-cjs-default
Package exportsexports: true - Auto-generate exports fieldoption-package-exports
CSS handling[experimental] css: { ... } — full pipeline with preprocessors, Lightning CSS, PostCSS, code splitting; requires @tsdown/cssoption-css
CSS injectcss: { inject: true } — preserve CSS imports in JS outputoption-css
Unbundle modeunbundle: true - Preserve directory structureoption-unbundle
Root directoryroot: 'src' - Control output directory mappingoption-root
Executable[experimental] exe: true - Bundle as standalone executable, cross-platform via @tsdown/exeoption-exe
Package validationpublint: true, attw: true - Validate packageoption-lint

Framework & Runtime Support

FrameworkGuideReference
ReactJSX transform, React Compilerrecipe-react
VueSFC support, JSXrecipe-vue
SolidSolidJS JSX transformrecipe-solid
SvelteSvelte component libraries (source distribution recommended)recipe-svelte
WASMWebAssembly modules via rolldown-plugin-wasmrecipe-wasm

Common Patterns

Basic Library Bundle

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  clean: true,
})

Multiple Entry Points

export default defineConfig({
  entry: {
    index: 'src/index.ts',
    utils: 'src/utils.ts',
    cli: 'src/cli.ts',
  },
  format: ['esm', 'cjs'],
  dts: true,
})

Browser Library (IIFE/UMD)

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['iife'],
  globalName: 'MyLib',
  platform: 'browser',
  minify: true,
})

React Component Library

export default defineConfig({
  entry: ['src/index.tsx'],
  format: ['esm', 'cjs'],
  dts: true,
  deps: {
    neverBundle: ['react', 'react-dom'],
  },
  inputOptions: {
    jsx: {runtime: 'automatic'},
  },
})

Preserve Directory Structure

export default defineConfig({
  entry: ['src/**/*.ts', '!**/*.test.ts'],
  unbundle: true, // Preserve file structure
  format: ['esm'],
  dts: true,
})

CI-Aware Configuration

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  failOnWarn: 'ci-only', // opt-in: fail on warnings in CI
  publint: 'ci-only',
  attw: 'ci-only',
})

WASM Support

import {wasm} from 'rolldown-plugin-wasm'
import {defineConfig} from 'tsdown'

export default defineConfig({
  entry: ['src/index.ts'],
  plugins: [wasm()],
})

Library with CSS and Sass

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  target: 'chrome100',
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "src/styles/variables" as *;`,
      },
    },
  },
})

Standalone Executable

export default defineConfig({
  entry: ['src/cli.ts'],
  exe: true,
})

Cross-Platform Executable (requires @tsdown/exe)

export default defineConfig({
  entry: ['src/cli.ts'],
  exe: {
    targets: [
      {platform: 'linux', arch: 'x64', nodeVersion: '25.7.0'},
      {platform: 'darwin', arch: 'arm64', nodeVersion: '25.7.0'},
      {platform: 'win', arch: 'x64', nodeVersion: '25.7.0'},
    ],
  },
})

Advanced with Hooks

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  hooks: {
    'build:before': async (context) => {
      console.log('Building...')
    },
    'build:done': async (context) => {
      console.log('Build complete!')
    },
  },
})

Configuration Features

Multiple Configs

Export an array for multiple build configurations:

export default defineConfig([
  {
    entry: ['src/index.ts'],
    format: ['esm', 'cjs'],
    dts: true,
  },
  {
    entry: ['src/cli.ts'],
    format: ['esm'],
    platform: 'node',
  },
])

Conditional Config

Use functions for dynamic configuration:

export default defineConfig((options) => {
  const isDev = options.watch
  return {
    entry: ['src/index.ts'],
    format: ['esm', 'cjs'],
    minify: !isDev,
    sourcemap: isDev,
  }
})

Workspace/Monorepo

Use glob patterns to build multiple packages:

export default defineConfig({
  workspace: 'packages/*',
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
})

CLI Quick Reference

# Basic commands
tsdown                          # Build once
tsdown --watch                  # Watch mode
tsdown --config custom.ts       # Custom config
npx tsdown-migrate              # Migrate from tsup

# Output options
tsdown --format esm,cjs        # Multiple formats
tsdown -d lib                  # Custom output directory (--out-dir)
tsdown --minify                # Enable minification
tsdown --dts                   # Generate declarations
tsdown --exe                   # Bundle as standalone executable
tsdown --unbundle              # Bundleless mode

# Entry options
tsdown src/index.ts            # Single entry
tsdown src/*.ts                # Glob patterns
tsdown src/a.ts src/b.ts       # Multiple entries

# Workspace / Monorepo
tsdown -W                      # Enable workspace mode
tsdown -W -F my-package        # Filter specific package
tsdown --filter /^pkg-/        # Filter by regex

# Development
tsdown --watch                 # Watch mode
tsdown --sourcemap             # Generate source maps
tsdown --clean                 # Clean output directory
tsdown --from-vite             # Reuse Vite config
tsdown --tsconfig tsconfig.build.json  # Custom tsconfig

Best Practices

  1. Always generate type declarations for TypeScript libraries:

    {
      dts: true
    }
    
  2. Externalize dependencies to avoid bundling unnecessary code:

    {
      deps: {
        neverBundle: [/^react/, /^@myorg\//]
      }
    }
    
  3. Use tree shaking for optimal bundle size:

    {
      treeshake: true
    }
    
  4. Enable minification for production builds:

    {
      minify: true
    }
    
  5. Add shims for better ESM/CJS compatibility:

    {
      shims: true
    } // Adds __dirname, __filename, etc.
    
  6. Auto-generate package.json exports:

    {
      exports: true
    } // Creates proper exports field
    
  7. Use watch mode during development:

    tsdown --watch
    
  8. Preserve structure for utilities with many files:

    {
      unbundle: true
    } // Keep directory structure
    
  9. Validate packages in CI before publishing:

    { publint: 'ci-only', attw: 'ci-only' }
    

Resources

來自 sanity-io 的更多技能

sanity-migration
sanity-io
規劃、執行並審查從其他內容管理系統及內容平台遷移至 Sanity 的作業。適用於從 AEM、Adobe Experience Manager、Contentful、Strapi、Webflow、WordPress、Payload、Drupal、Markdown/MDX/frontmatter 檔案、WXR/XML 匯出、CMS API、資料庫匯出、靜態 HTML 進行遷移或平台轉換,或設計資料擷取、轉換、Portable Text 轉換、資產遷移、重新導向、驗證及切換流程時使用。
officialdevelopmentdatabase
create-agent-with-sanity-context
sanity-io
透過 Agent Context 建立對 Sanity 內容有結構化存取權限的 AI 代理。適用於設定由 Sanity 驅動的聊天機器人、將 AI 助手連接到 Sanity…
official
dial-your-context
sanity-io
互動式工作階段,用於為 Sanity Agent Context MCP 建立「指令」欄位內容。每當使用者提及調整代理上下文、改善…時,請使用此技能。
official
optimize-agent-prompt
sanity-io
透過引導式對話調整您的 Sanity Agent Context 代理。將探索數據轉換為可投入生產的指令,並精心設計系統提示…
official
shape-your-agent
sanity-io
互動式工作階段,用於為由 Sanity Agent Context MCP 驅動的 AI 代理設計系統提示。當使用者想要定義代理人格時,請使用此技能…
official
content-experimentation-best-practices
sanity-io
結構化指引,涵蓋設計、執行與分析內容實驗以提升轉換率與參與度。內容包括假設框架、指標選擇、樣本數計算,以及A/B測試與多變量實驗中的統計顯著性檢定。提供關於p值、信賴區間、統計檢定力分析及貝氏方法的詳細資源,用於解讀實驗結果。同時包含CMS整合模式,以便在欄位層級管理變體,並連接外部系統。
official
content-modeling-best-practices
sanity-io
結構化內容建模指南,涵蓋綱要設計、可重用性與多渠道發布。核心原則包括:將內容視為數據而非頁面、維護單一事實來源、為未來渠道設計,以及優化編輯工作流程。提供關於引用與嵌入物件、關注點分離及內容重用模式的決策框架。包含針對扁平、階層與分面分類法的分類學指引。適用於...
official
portable-text-conversion
sanity-io
將 HTML 和 Markdown 內容轉換為適用於 Sanity 的可攜式文字區塊。用於從舊版 CMS 遷移內容、將 HTML 或 Markdown 匯入 Sanity 等情境。
official