mcpField
T
tsdown

tsdown

github.com/antfu开发6.0k14.0k 次安装6 天前更新
代码仓库

关于 tsdown

tsdown 是面向 TypeScript 和 JavaScript 库作者的打包器文档技能,介绍从配置到输出优化的构建选项。内容涵盖多种模块格式、类型声明、依赖处理及迁移自 tsup 的指南。

主要功能

  1. 01生成多种输出格式
  2. 02生成 TypeScript 类型声明
  3. 03配置依赖打包与外部化
  4. 04支持树摇和压缩
  5. 05提供 tsup 迁移指南

适用场景

  1. 01构建 npm 库并生成类型声明
  2. 02为不同平台设置构建目标
  3. 03在 CI 中验证发布包

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/antfu/skills --skill tsdown

安装后在 Claude Code 中输入/tsdown确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE.md
README.md
references/
advanced-benchmark.md
advanced-ci.md
advanced-hooks.md
advanced-plugins.md
advanced-programmatic.md
advanced-rolldown-options.md
guide-getting-started.md
guide-introduction.md
guide-migrate-from-tsup.md
option-cjs-default.md
option-cleaning.md
option-config-file.md
option-css.md
option-dependencies.md
option-dts.md
option-entry.md
option-exe.md
option-lint.md
option-log-level.md
option-minification.md
option-output-directory.md
option-output-format.md
option-package-exports.md
option-platform.md
option-root.md
option-shims.md
option-sourcemap.md
option-target.md

详细介绍

tsdown - 优雅的库打包器

由 Rolldown 和 Oxc 驱动的超高速 TypeScript/JavaScript 库打包器。

运行时要求

tsdown 需要 Node.js 22.18.0 或更高版本才能运行(仅限构建时)。不过,通过 target 选项,打包后的输出可以面向低得多的 Node.js 版本,因此使用 tsdown 构建的库在运行时并不局限于 Node.js 22+。

如果你的包需要支持 Node.js 18 / 20:

  • 在 CI 中使用 Node.js 22+ 进行构建(例如设置 target: 'node18' 或 target: 'node20')。
  • 在你计划支持的较低版本 Node.js 上测试构建产物(或打包后的 tarball)——例如,使用矩阵任务在 Node.js 18 / 20 / 22 上运行已发布包的测试。

适用场景

  • 为 npm 构建 TypeScript/JavaScript 库
  • 生成 TypeScript 声明文件(.d.ts)
  • 为多种格式打包(ESM、CJS、IIFE、UMD)
  • 使用 tree shaking 和压缩来优化打包产物
  • 以最少改动从 tsup 迁移
  • 构建 React、Vue、Solid 或 Svelte 组件库

快速开始

# 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

基本配置

import { defineConfig } from 'tsdown'

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

核心参考

主题说明参考
入门指南安装、首次打包、CLI 基础知识guide-getting-started
配置文件配置文件格式、多份配置、工作区option-config-file
CLI 参考所有 CLI 命令和选项reference-cli
从 tsup 迁移迁移指南和兼容性说明guide-migrate-from-tsup
插件支持 Rolldown、Rollup、Unpluginadvanced-plugins

如需全面的迁移帮助和完整的选项映射,请安装专用的 tsdown-migrate 技能:npx skills add rolldown/tsdown --skill tsdown-migrate | 钩子 | 用于自定义逻辑的生命周期钩子 | advanced-hooks | | 编程式 API | 从 Node.js 脚本执行构建 | advanced-programmatic | | Rolldown 选项 | 直接向 Rolldown 传递选项 | advanced-rolldown-options | | CI 环境 | CI 检测、'ci-only' / 'local-only' 值 | advanced-ci |

构建选项

选项用法参考
入口点entry: ['src/*.ts', '!**/*.test.ts']option-entry
输出格式format: ['esm', 'cjs', 'iife', 'umd']option-output-format
输出目录outDir: 'dist'、outExtensionsoption-output-directory
类型声明dts: true、dts: { sourcemap, compilerOptions, vue }option-dts
目标环境target: 'es2020'、target: 'esnext'option-target
平台platform: 'node'、platform: 'browser'option-platform
Tree shakingtreeshake: true、自定义选项option-tree-shaking
压缩minify: true、minify: 'dce-only'option-minification
Source mapsourcemap: true、'inline'、'hidden'option-sourcemap
监听模式watch: true、监听选项option-watch-mode
清理clean: true、清理模式option-cleaning
日志级别logLevel: 'silent'、failOnWarn: falseoption-log-level

依赖处理

功能用法参考
从不打包deps: { neverBundle: ['react', /^@myorg\//] }option-dependencies
始终打包deps: { alwaysBundle: ['dep-to-bundle'] }option-dependencies
仅打包指定依赖deps: { onlyBundle: ['cac', 'bumpp'] } - 白名单option-dependencies
跳过 node_modulesdeps: { skipNodeModulesBundle: true }option-dependencies
自动外部化自动外部化依赖、peer 和可选依赖option-dependencies

输出增强

功能用法参考
垫片shims: true - 添加 ESM/CJS 兼容性option-shims
CJS 默认导出cjsDefault: true(默认)/ falseoption-cjs-default
包导出exports: true - 生成 exports 字段option-package-exports
CSS 处理[experimental] css: { ... } — 完整处理管线,支持预处理器、Lightning CSS、PostCSS、CSS 模块和代码拆分;需要 @tsdown/cssoption-css
CSS 模块css: { modules: { localsConvention: 'camelCase' } } — 为 .module.css 文件生成作用域类名option-css
注入 CSScss: { inject: true } — 在 JS 输出中保留 CSS 导入option-css
不打包模式unbundle: true - 保留目录结构option-unbundle
根目录root: 'src' - 控制输出目录映射option-root
可执行文件[experimental] exe: true - 打包为独立可执行文件,通过 @tsdown/exe 支持跨平台option-exe
包验证publint: true, attw: true - 验证包option-lint

框架与运行时支持

框架指南参考
ReactJSX 转换、React Compilerrecipe-react
VueSFC 支持、JSXrecipe-vue
SolidSolidJS JSX 转换recipe-solid
SvelteSvelte 组件库(建议使用源码分发)recipe-svelte
WASM通过 rolldown-plugin-wasm 使用 WebAssembly 模块recipe-wasm

常见模式

基础库打包
export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  clean: true,
})
多个入口点
export default defineConfig({
  entry: {
    index: 'src/index.ts',
    utils: 'src/utils.ts',
    cli: 'src/cli.ts',
  },
  format: ['esm', 'cjs'],
  dts: true,
})
浏览器库(IIFE/UMD)
export default defineConfig({
  entry: ['src/index.ts'],
  format: ['iife'],
  globalName: 'MyLib',
  platform: 'browser',
  minify: true,
})
React 组件库
export default defineConfig({
  entry: ['src/index.tsx'],
  format: ['esm', 'cjs'],
  dts: true,
  deps: {
    neverBundle: ['react', 'react-dom'],
  },
  inputOptions: {
    jsx: { runtime: 'automatic' },
  },
})
保留目录结构
export default defineConfig({
  entry: ['src/**/*.ts', '!**/*.test.ts'],
  unbundle: true, // Preserve file structure
  format: ['esm'],
  dts: true,
})
CI 感知配置
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 支持
import { wasm } from 'rolldown-plugin-wasm'
import { defineConfig } from 'tsdown'

export default defineConfig({
  entry: ['src/index.ts'],
  plugins: [wasm()],
})
带 CSS 和 Sass 的库
export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  target: 'chrome100',
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "src/styles/variables" as *;`,
      },
    },
  },
})
独立可执行文件
export default defineConfig({
  entry: ['src/cli.ts'],
  exe: true,
})
跨平台可执行文件(需要 @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' },
    ],
  },
})
使用钩子的高级配置
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!')
    },
  },
})

配置功能

多个配置

导出一个数组以配置多个构建:

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

使用函数实现动态配置:

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

使用 glob 模式构建多个包:

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

CLI 速查

# 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

最佳实践

  1. 始终为 TypeScript 库生成类型声明:

    { dts: true }
    
  2. 将依赖项设为外部依赖,避免打包不必要的代码:

    { deps: { neverBundle: [/^react/, /^@myorg\//] } }
    
  3. 使用 tree shaking,优化打包体积:

    { treeshake: true }
    
  4. 为生产构建启用压缩:

    { minify: true }
    
  5. 添加 shim,提高 ESM/CJS 兼容性:

    { shims: true }  // Adds __dirname, __filename, etc.
    
  6. 自动生成 package.json 导出配置:

    { exports: true }  // Creates proper exports field
    
  7. 在开发期间使用监视模式:

    tsdown --watch
    
  8. 为包含许多文件的工具保留目录结构:

    { unbundle: true }  // Keep directory structure
    
  9. 在发布前于 CI 中验证软件包:

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

资源

评论

支持 Markdown