> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# esbuild

> 从 esbuild 迁移到 Bun 的打包器指南

Bun 的打包器 API 深受 esbuild 的启发。从 esbuild 迁移到 Bun 的打包器应该相对简单。本文档将简要说明为何你可能考虑迁移到 Bun 的打包器，并且为那些已经熟悉 esbuild API 的用户提供并排的 API 对比参考。

这里有一些行为上的差异需要注意。

<Note>
  **默认进行打包。** 与 esbuild 不同，Bun 默认总是进行打包。这就是为何 Bun 的示例中不需要 `--bundle` 标志。要对每个文件单独转译，请使用 `Bun.Transpiler`。
</Note>

<Note>
  **仅打包器。** 与 esbuild 不同，Bun 的打包器不包含内置的开发服务器或文件监听器。该
  打包器旨在与 `Bun.serve` 和其他运行时 API 结合使用，以达到相同的效果。因此，所有与 HTTP/文件监听相关的选项都不适用。
</Note>

## 性能

凭借性能优先的 API 及经过大量优化的基于 Zig 的 JS/TS 解析器，Bun 的打包器在 esbuild 的 three.js 性能基准上比 esbuild 快 1.75 倍。

<Info>从零开始打包 10 份 three.js，启用源码映射和压缩</Info>

## CLI API

Bun 和 esbuild 都提供了命令行接口。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
# esbuild
esbuild <entrypoint> --outdir=out --bundle

# bun
bun build <entrypoint> --outdir=out
```

在 Bun 的 CLI 中，简单的布尔标志如 `--minify` 不接受参数。其他带参数的标志如 `--outdir <path>` 接受参数；这类标志可以写成 `--outdir out` 或 `--outdir=out`。有些标志如 `--define` 可以多次指定：`--define foo=bar --define bar=baz`。

| esbuild                | bun build                  | 说明                                                                                                                                                                                                                                    |
| ---------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--bundle`             | 不适用                        | Bun 总是进行打包，使用 `--no-bundle` 关闭此行为。                                                                                                                                                                                                    |
| `--define:K=V`         | `--define K=V`             | 语法小差异；无冒号。<br />`esbuild --define:foo=bar`<br />`bun build --define foo=bar`                                                                                                                                                          |
| `--external:<pkg>`     | `--external <pkg>`         | 语法小差异；无冒号。<br />`esbuild --external:react`<br />`bun build --external react`                                                                                                                                                          |
| `--format`             | `--format`                 | Bun 当前支持 `"esm"` 和 `"cjs"`，更多模块格式计划支持。esbuild 默认 `"iife"`。                                                                                                                                                                            |
| `--loader:.ext=loader` | `--loader .ext:loader`     | Bun 支持的内置加载器集合与 esbuild 不同；详见打包器 > 加载器完整参考。esbuild 的 `dataurl`、`binary`、`base64`、`copy` 和 `empty` 加载器尚未实现。<br /><br />`--loader` 语法稍有区别。<br />`esbuild app.ts --bundle --loader:.svg=text`<br />`bun build app.ts --loader .svg:text` |
| `--minify`             | `--minify`                 | 无区别                                                                                                                                                                                                                                   |
| `--outdir`             | `--outdir`                 | 无区别                                                                                                                                                                                                                                   |
| `--outfile`            | `--outfile`                | 无区别                                                                                                                                                                                                                                   |
| `--packages`           | `--packages`               | 无区别                                                                                                                                                                                                                                   |
| `--platform`           | `--target`                 | 重命名为 `--target`，以与 tsconfig 保持一致。不支持 `neutral`。                                                                                                                                                                                       |
| `--serve`              | 不适用                        | 不适用                                                                                                                                                                                                                                   |
| `--sourcemap`          | `--sourcemap`              | 无区别                                                                                                                                                                                                                                   |
| `--splitting`          | `--splitting`              | 无区别                                                                                                                                                                                                                                   |
| `--target`             | 不适用                        | 不支持。Bun 的打包器目前不支持语法层级降级。                                                                                                                                                                                                              |
| `--watch`              | `--watch`                  | 无区别                                                                                                                                                                                                                                   |
| `--allow-overwrite`    | 不适用                        | 不允许覆盖                                                                                                                                                                                                                                 |
| `--analyze`            | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--asset-names`        | `--asset-naming`           | 重命名以统一 JS API 命名                                                                                                                                                                                                                      |
| `--banner`             | `--banner`                 | 仅应用于 js 打包                                                                                                                                                                                                                            |
| `--footer`             | `--footer`                 | 仅应用于 js 打包                                                                                                                                                                                                                            |
| `--certfile`           | 不适用                        | 不适用                                                                                                                                                                                                                                   |
| `--charset=utf8`       | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--chunk-names`        | `--chunk-naming`           | 重命名以统一 JS API 命名                                                                                                                                                                                                                      |
| `--color`              | 不适用                        | 始终启用                                                                                                                                                                                                                                  |
| `--drop`               | `--drop`                   |                                                                                                                                                                                                                                       |
| 不适用                    | `--feature`                | Bun 特有。通过 `import { feature } from "bun:bundle"` 启用编译时死代码消除的特性标志                                                                                                                                                                      |
| `--entry-names`        | `--entry-naming`           | 重命名以统一 JS API 命名                                                                                                                                                                                                                      |
| `--global-name`        | 不适用                        | 不适用，Bun 目前不支持 `iife` 输出                                                                                                                                                                                                               |
| `--ignore-annotations` | `--ignore-dce-annotations` |                                                                                                                                                                                                                                       |
| `--inject`             | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--jsx`                | `--jsx-runtime <runtime>`  | 支持 `"automatic"`（使用 jsx 转换）和 `"classic"`（使用 `React.createElement`）                                                                                                                                                                    |
| `--jsx-dev`            | 不适用                        | Bun 从 `tsconfig.json` 的 `compilerOptions.jsx` 读取默认值。若值为 `"react-jsx"` 或环境变量 `NODE_ENV=production`，Bun 会使用 jsx 转换，否则使用 `jsxDEV`。打包器不支持 `preserve`。                                                                                     |
| `--jsx-factory`        | `--jsx-factory`            |                                                                                                                                                                                                                                       |
| `--jsx-fragment`       | `--jsx-fragment`           |                                                                                                                                                                                                                                       |
| `--jsx-import-source`  | `--jsx-import-source`      |                                                                                                                                                                                                                                       |
| `--jsx-side-effects`   | 不适用                        | JSX 始终被假定为无副作用                                                                                                                                                                                                                        |
| `--keep-names`         | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--keyfile`            | 不适用                        | 不适用                                                                                                                                                                                                                                   |
| `--legal-comments`     | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--log-level`          | 不适用                        | 不支持，可在 `bunfig.toml` 通过 `logLevel` 设置                                                                                                                                                                                                 |
| `--log-limit`          | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--log-override:X=Y`   | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--main-fields`        | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--mangle-cache`       | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--mangle-props`       | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--mangle-quoted`      | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--metafile`           | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--minify-whitespace`  | `--minify-whitespace`      |                                                                                                                                                                                                                                       |
| `--minify-identifiers` | `--minify-identifiers`     |                                                                                                                                                                                                                                       |
| `--minify-syntax`      | `--minify-syntax`          |                                                                                                                                                                                                                                       |
| `--out-extension`      | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--outbase`            | `--root`                   |                                                                                                                                                                                                                                       |
| `--preserve-symlinks`  | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--public-path`        | `--public-path`            |                                                                                                                                                                                                                                       |
| `--pure`               | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--reserve-props`      | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--resolve-extensions` | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--servedir`           | 不适用                        | 不适用                                                                                                                                                                                                                                   |
| `--source-root`        | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--sourcefile`         | 不适用                        | 不支持，Bun 目前不支持标准输入输入。                                                                                                                                                                                                                  |
| `--sourcemap`          | `--sourcemap`              | 无区别                                                                                                                                                                                                                                   |
| `--sources-content`    | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--supported`          | 不适用                        | 不支持                                                                                                                                                                                                                                   |
| `--tree-shaking`       | 不适用                        | 始终开启                                                                                                                                                                                                                                  |
| `--tsconfig`           | `--tsconfig-override`      |                                                                                                                                                                                                                                       |
| `--version`            | 不适用                        | 运行 `bun --version` 查看 Bun 版本                                                                                                                                                                                                          |

## JavaScript API

| esbuild.build()     | Bun.build()               | 说明                                                                                                                                                                                                                                                                                                                                                             |
| ------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `absWorkingDir`     | 不适用                       | 总是设置为 `process.cwd()`                                                                                                                                                                                                                                                                                                                                          |
| `alias`             | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `allowOverwrite`    | 不适用                       | 总是为 false                                                                                                                                                                                                                                                                                                                                                      |
| `assetNames`        | `naming.asset`            | 使用与 esbuild 相同的模板语法，但必须显式包含 `[ext]`。<br /><br />`ts<br/>Bun.build({<br/>  entrypoints: ["./index.tsx"],<br/>  naming: {<br/>    asset: "[name].[ext]",<br/>  },<br/>});<br/>`                                                                                                                                                                                  |
| `banner`            | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `bundle`            | 不适用                       | 总是开启。若不想打包，请使用 `Bun.Transpiler` 进行转译。                                                                                                                                                                                                                                                                                                                          |
| `charset`           | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `chunkNames`        | `naming.chunk`            | 使用与 esbuild 相同的模板语法，但必须显式包含 `[ext]`。<br /><br />`ts<br/>Bun.build({<br/>  entrypoints: ["./index.tsx"],<br/>  naming: {<br/>    chunk: "[name].[ext]",<br/>  },<br/>});<br/>`                                                                                                                                                                                  |
| `color`             | 不适用                       | Bun 会在构建结果的 `logs` 属性中返回日志内容。                                                                                                                                                                                                                                                                                                                                  |
| `conditions`        | 不适用                       | 不支持。导出条件优先级由 `target` 决定。                                                                                                                                                                                                                                                                                                                                      |
| `define`            | `define`                  |                                                                                                                                                                                                                                                                                                                                                                |
| `drop`              | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `entryNames`        | `naming` 或 `naming.entry` | Bun 支持 `naming` 键，既可以是字符串也可以是对象。使用与 esbuild 相同的模板语法，但必须显式包含 `[ext]`。<br /><br />`ts<br/>Bun.build({<br/>  entrypoints: ["./index.tsx"],<br/>  // 如果为字符串，相当于 entryNames<br/>  naming: "[name].[ext]",<br/><br/>  // 细粒度命名选项<br/>  naming: {<br/>    entry: "[name].[ext]",<br/>    asset: "[name].[ext]",<br/>    chunk: "[name].[ext]",<br/>  },<br/>});<br/>` |
| `entryPoints`       | `entrypoints`             | 大小写差异                                                                                                                                                                                                                                                                                                                                                          |
| `external`          | `external`                | 无区别                                                                                                                                                                                                                                                                                                                                                            |
| `footer`            | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `format`            | `format`                  | 目前仅支持 `"esm"`。计划支持 `"cjs"` 和 `"iife"`。                                                                                                                                                                                                                                                                                                                         |
| `globalName`        | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `ignoreAnnotations` | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `inject`            | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `jsx`               | `jsx`                     | JS API 中不支持，通过 `tsconfig.json` 配置                                                                                                                                                                                                                                                                                                                              |
| `jsxDev`            | `jsxDev`                  | JS API 中不支持，通过 `tsconfig.json` 配置                                                                                                                                                                                                                                                                                                                              |
| `jsxFactory`        | `jsxFactory`              | JS API 中不支持，通过 `tsconfig.json` 配置                                                                                                                                                                                                                                                                                                                              |
| `jsxFragment`       | `jsxFragment`             | JS API 中不支持，通过 `tsconfig.json` 配置                                                                                                                                                                                                                                                                                                                              |
| `jsxImportSource`   | `jsxImportSource`         | JS API 中不支持，通过 `tsconfig.json` 配置                                                                                                                                                                                                                                                                                                                              |
| `jsxSideEffects`    | `jsxSideEffects`          | JS API 中不支持，通过 `tsconfig.json` 配置                                                                                                                                                                                                                                                                                                                              |
| `keepNames`         | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `legalComments`     | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `loader`            | `loader`                  | Bun 支持的内置加载器集合与 esbuild 不同；详见打包器 > 加载器完整参考。esbuild 的 `dataurl`、`binary`、`base64`、`copy` 和 `empty` 加载器尚未实现。                                                                                                                                                                                                                                                     |
| `logLevel`          | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `logLimit`          | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `logOverride`       | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `mainFields`        | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `mangleCache`       | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `mangleProps`       | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `mangleQuoted`      | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `metafile`          | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `minify`            | `minify`                  | 在 Bun 中，`minify` 可以是布尔值或对象。<br /><br />`ts<br/>await Bun.build({<br/>  entrypoints: ['./index.tsx'],<br/>  // 启用全部压缩<br/>  minify: true<br/><br/>  // 细粒度配置<br/>  minify: {<br/>    identifiers: true,<br/>    syntax: true,<br/>    whitespace: true<br/>  }<br/>})<br/>`                                                                                     |
| `minifyIdentifiers` | `minify.identifiers`      | 参见 `minify`                                                                                                                                                                                                                                                                                                                                                    |
| `minifySyntax`      | `minify.syntax`           | 参见 `minify`                                                                                                                                                                                                                                                                                                                                                    |
| `minifyWhitespace`  | `minify.whitespace`       | 参见 `minify`                                                                                                                                                                                                                                                                                                                                                    |
| `nodePaths`         | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `outExtension`      | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `outbase`           | `root`                    | 名称不同                                                                                                                                                                                                                                                                                                                                                           |
| `outdir`            | `outdir`                  | 无区别                                                                                                                                                                                                                                                                                                                                                            |
| `outfile`           | `outfile`                 | 无区别                                                                                                                                                                                                                                                                                                                                                            |
| `packages`          | 不适用                       | 不支持，请使用 `external`                                                                                                                                                                                                                                                                                                                                             |
| `platform`          | `target`                  | 支持 `"bun"`、`"node"` 和 `"browser"`（默认）。不支持 `"neutral"`。                                                                                                                                                                                                                                                                                                         |
| `plugins`           | `plugins`                 | Bun 的插件 API 是 esbuild 的子集。一些 esbuild 插件可开箱即用地在 Bun 下工作。                                                                                                                                                                                                                                                                                                        |
| `preserveSymlinks`  | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `publicPath`        | `publicPath`              | 无区别                                                                                                                                                                                                                                                                                                                                                            |
| `pure`              | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `reserveProps`      | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `resolveExtensions` | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `sourceRoot`        | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `sourcemap`         | `sourcemap`               | 支持 `"inline"`、`"external"` 和 `"none"`                                                                                                                                                                                                                                                                                                                          |
| `sourcesContent`    | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `splitting`         | `splitting`               | 无区别                                                                                                                                                                                                                                                                                                                                                            |
| `stdin`             | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `supported`         | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `target`            | 不适用                       | 不支持语法层级降级                                                                                                                                                                                                                                                                                                                                                      |
| `treeShaking`       | 不适用                       | 始终开启                                                                                                                                                                                                                                                                                                                                                           |
| `tsconfig`          | 不适用                       | 不支持                                                                                                                                                                                                                                                                                                                                                            |
| `write`             | 不适用                       | 如果设置了 `outdir` 或 `outfile`，则为 true，否则 false                                                                                                                                                                                                                                                                                                                    |

## 插件 API

Bun 的插件 API 设计为与 esbuild 兼容。Bun 尚未支持 esbuild 的全部插件 API，但核心功能已经实现。许多第三方 esbuild 插件可开箱即用地在 Bun 中工作。

<Note>
  从长远来看，我们的目标是实现与 esbuild API 功能等价；如果遇到任何不兼容，请提出 issue 以协助我们确定优先级。
</Note>

Bun 和 esbuild 中的插件均通过构造一个 builder 对象定义。

```ts title="myPlugin.ts" icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import type { BunPlugin } from "bun";

const myPlugin: BunPlugin = {
  name: "my-plugin",
  setup(builder) {
    // 定义插件
  },
};
```

builder 对象提供了一些方法，用于挂钩打包过程中的各个部分。Bun 实现了 `onStart`、`onEnd`、`onResolve` 和 `onLoad`。它目前还没有实现 esbuild 的 hooks `onDispose` 和 `resolve`。`initialOptions` 已部分实现：它是只读的，并且只有 esbuild 选项的一个子集；请改用 `config`（同样的含义，但使用 Bun 的 `BuildConfig` 格式）。

```ts title="myPlugin.ts" icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
  name: "my-plugin",
  setup(builder) {
    builder.onStart(() => {
      /* 当打包开始时调用 */
    });
    builder.onResolve(
      {
        /* onResolve.options */
      },
      args => {
        return {
          /* onResolve.results */
        };
      },
    );
    builder.onLoad(
      {
        /* onLoad.options */
      },
      args => {
        return {
          /* onLoad.results */
        };
      },
    );
    builder.onEnd(result => {
      /* 当打包完成时调用 */
    });
  },
};
```

### onResolve

<Tabs>
  <Tab title="选项">
    * 🟢 `filter`
    * 🟢 `namespace`
  </Tab>

  <Tab title="参数">
    * 🟢 `path`
    * 🟢 `importer`
    * 🔴 `namespace`
    * 🔴 `resolveDir`
    * 🔴 `kind`
    * 🔴 `pluginData`
  </Tab>

  <Tab title="返回值">
    * 🟢 `namespace`
    * 🟢 `path`
    * 🔴 `errors`
    * 🔴 `external`
    * 🔴 `pluginData`
    * 🔴 `pluginName`
    * 🔴 `sideEffects`
    * 🔴 `suffix`
    * 🔴 `warnings`
    * 🔴 `watchDirs`
    * 🔴 `watchFiles`
  </Tab>
</Tabs>

### onLoad

<Tabs>
  <Tab title="选项">
    * 🟢 `filter`
    * 🟢 `namespace`
  </Tab>

  <Tab title="参数">
    * 🟢 `path`
    * 🔴 `namespace`
    * 🔴 `suffix`
    * 🔴 `pluginData`
  </Tab>

  <Tab title="返回值">
    * 🟢 `contents`
    * 🟢 `loader`
    * 🔴 `errors`
    * 🔴 `pluginData`
    * 🔴 `pluginName`
    * 🔴 `resolveDir`
    * 🔴 `warnings`
    * 🔴 `watchDirs`
    * 🔴 `watchFiles`
  </Tab>
</Tabs>
