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
다른 CMS 및 콘텐츠 시스템에서 Sanity로의 마이그레이션을 계획, 구현 및 검토합니다. AEM, Adobe Experience Manager, Contentful, Strapi, Webflow, WordPress, Payload, Drupal, Markdown/MDX/frontmatter 파일, WXR/XML 내보내기, CMS API, 데이터베이스 덤프, 정적 HTML에서 Sanity로 마이그레이션하거나 리플랫폼할 때, 또는 추출, 변환, 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의 Instructions 필드 콘텐츠를 생성합니다. 사용자가 에이전트 컨텍스트 튜닝, 개선 등을 언급할 때 이 스킬을 사용하세요.
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용 Portable Text 블록으로 변환합니다. 레거시 CMS에서 콘텐츠를 마이그레이션하거나 HTML 또는 Markdown을 Sanity로 가져올 때 사용합니다.
official