Skip to content
/ BundleTools/Tsup
3/27/2024
3.1m
AI 摘要

tsup 是基于 esbuild 的快速打包工具,支持 tsjs 等多种格式,提供 --watch--dts--minify 等常用选项,并支持 tree shakingcustom loaderpostcss 等功能,适合打包 TypeScript 库。

Tsup

tsup 是捆绑 TypeScript 库的最简单、最快的方法。原生支持 ts,js,json,tsx,mjs 的打包。

特点

tsup 也是基于其他打包工具的封装,主要是 esbuild 为主,某些情况下会用到 rollup 或者 swc 等。

如果开发一个 ts 库,tsup 是一个非常合适的打包工具的选择。

它提供了丰富的命令行和配置选项,让我们可以得到丰富多样的打包产物

常用选项

tsup src/index.ts --watch
tsup src/index.ts --dts # dts 生成,可以指定单个文件
tsup src/index.ts --dtsOnly # 单 dts 生成
tsup src/index.ts --minify # 压缩,可以指定使用 terser
tsup src/index.ts --sourcemap # 可以指定 inline 模式
tsup src/index.ts --clean # 构建前清除 dist
tsup src/index.ts --format esm,cjs,iife

external

默认情况下,package.json 中的 dependenciespeerDependencies 中的包将视为 external,即不会被解析,也可以通过 --external <module|pkgJson> 手动指定其他包或者 package.json 文件

默认还提供了一个命令,来排除所有的 Nodejs 包。

tsup-node src/index.ts

onSuccess

通过 onSuccess ,可以指定成功构建后要执行的命令,对于 watch 模式特别有用:

tsup src/index.ts --watch --onSuccess "cp -r dist/* ../../public"

或者是回调函数的形式,通过 tsup.config.ts 来配置:

import { defineConfig } from 'tsup'

export default defineConfig({
  async onSuccess() {
    // Start some long running task
    // Like a server
  },
})

conditional config

tsup 还有一个有意思的功能是,如果需要根据 CLI 标志有条件地确定配置,可以支持导出函数,使配置更加灵活:

import { defineConfig } from 'tsup'

export default defineConfig((options) => {
  return {
    minify: !options.watch,
  }
})

Tree sharking

esbuildtree sharking 在某些情况下有问题,可以通过手动指定 --treeshake 来启用 rollup 的 tree shaking

tsup src/index.ts --treeshake

环境变量

通过 --env 指定环境变量

tsup src/index.ts --env.NODE_ENV production

target

通过指定 target 选项来设置生成的 JavaScript 和/或 CSS 代码的目标环境

  • chrome
  • edge
  • firefox
  • hermes
  • ...

自定义 Loader

自己定义对文件处理时的 loader

type Loader =
  | 'js'
  | 'jsx'
  | 'ts'
  | 'tsx'
  | 'css'
  | 'json'
  | 'text'
  | 'base64'
  | 'file'
  | 'dataurl'
  | 'binary'
  | 'copy'
  | 'default'

可以通过 CLI 选项指定,查看更多

tsup --loader ".jpg=base64" --loader ".webp=file"

实验性的 CSS 支持

需要手动安装 postcss

yarn add postcss --dev

在项目中新增 postcss.config.js

module.exports = {
  plugins: [require('tailwindcss')(), require('autoprefixer')()],
}

插件

插件机制保持和 esbuild 一致:

import { defineConfig } from 'tsup'

export default defineConfig({
  esbuildPlugins: [YourPlugin],
  esbuildOptions(options, context) {
    options.define.foo = '"bar"'
  },
})

CJS/ESM shims

开启 shims 后

当构建 cjs 的时候,import.meta.url 会被转换为例如 typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href

当构建 esm 的时候,__dirname 会被转换为 path.dirname(fileURLToPath(import.meta.url))

Released under the MIT License.