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

# 打包器

> Bun 快速的 Web 原生打包器，支持 JavaScript、TypeScript、JSX 等

export const name_0 = undefined

使用 Bun 的原生打包器，通过 `bun build` CLI 命令或 `Bun.build()` JavaScript API。

### 一览

* JS API：`await Bun.build({ entrypoints, outdir })`
* CLI：`bun build <entry> --outdir ./out`
* 监视模式：`--watch` 用于增量重新构建
* 目标：`--target browser|bun|node`
* 格式：`--format esm|cjs|iife`（cjs/iife 为实验性）

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './build',
    });
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./build
    ```
  </Tab>
</Tabs>

它很快。以下数据来自 esbuild 的 [three.js 基准测试](https://github.com/oven-sh/bun/tree/main/bench/bundle)。

<Frame>
  <img src="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/images/bundler-speed.png?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=e167f6e0ad469743d30b233bc8d81a7d" caption="从零打包 10 份 three.js，带 sourcemap 和压缩" width="2690" height="1072" data-path="images/bundler-speed.png" />
</Frame>

## 为什么要打包？

打包器解决了几个问题：

* **减少 HTTP 请求。** `node_modules` 中的单个包可能包含数百个文件，大型应用可能有几十个这样的依赖。用单独的 HTTP 请求加载每个文件是不可行的，因此打包器将你的应用源代码转换为数量更少的自包含"包"，可以通过单个请求加载。
* **代码转换。** 现代应用通常使用 TypeScript、JSX 和 CSS 模块等语言或工具构建，所有这些在浏览器消费之前必须转换为普通 JavaScript 和 CSS。打包器是配置这些转换的自然位置。
* **框架功能。** 框架依赖打包器插件和代码转换来实现常见模式，如文件系统路由、客户端-服务器代码共置（比如 `getServerSideProps` 或 Remix loader）以及服务器组件。
* **全栈应用。** Bun 的打包器可以在单个命令中处理服务器和客户端代码，实现优化后的生产构建和单文件可执行文件。通过构建时的 HTML 导入，你可以将整个应用程序（前端资源和后端服务器）打包到一个可部署的单元中。

<Note>Bun 打包器不打算替代 `tsc` 进行类型检查或生成类型声明。</Note>

## 基本示例

构建你的第一个包。你有以下两个文件，实现了一个客户端渲染的 React 应用。

<CodeGroup>
  ```tsx index.tsx icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  import * as ReactDOM from "react-dom/client";
  import { Component } from "./Component";

  const root = ReactDOM.createRoot(document.getElementById("root")!);
  root.render(<Component message="Sup!" />);
  ```

  ```tsx Component.tsx icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  export function Component(props: { message: string }) {
    return <h1>{props.message}</h1>;
  }
  ```
</CodeGroup>

这里，`index.tsx` 是应用的"入口点"：打包器开始的文件。通常这是一个执行某些副作用的脚本，比如启动服务器，或者在本例中初始化 React 根节点。因为这些文件使用了 TypeScript 和 JSX，代码必须先打包才能发送到浏览器。

要创建包：

<CodeGroup>
  ```ts build.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  await Bun.build({
    entrypoints: ["./index.tsx"],
    outdir: "./out",
  });
  ```

  ```bash terminal icon="terminal" theme={null}
  bun build ./index.tsx --outdir ./out
  ```
</CodeGroup>

对于 `entrypoints` 中指定的每个文件，Bun 生成一个新的包并将其写入 `./out` 目录（从当前工作目录解析）。运行构建后，文件系统看起来像这样：

```text title="file system" icon="folder-tree" theme={null}
.
├── index.tsx
├── Component.tsx
└── out
    └── index.js
```

`out/index.js` 的内容看起来像这样：

```js title="out/index.js" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
// out/index.js
// ...
// 约 20k 行代码
// 包含 `react-dom/client` 及其所有依赖的内容
// 这里定义了 $jsxDEV 和 $createRoot 函数

// Component.tsx
function Component(props) {
  return $jsxDEV(
    "p",
    {
      children: props.message,
    },
    undefined,
    false,
    undefined,
    this,
  );
}

// index.tsx
var rootNode = document.getElementById("root");
var root = $createRoot(rootNode);
root.render(
  $jsxDEV(
    Component,
    {
      message: "Sup!",
    },
    undefined,
    false,
    undefined,
    this,
  ),
);
```

## 监视模式

与运行时和测试运行器一样，打包器原生支持监视模式。

```bash terminal icon="terminal" theme={null}
bun build ./index.tsx --outdir ./out --watch
```

## 内容类型

与 Bun 运行时一样，打包器默认支持一系列文件类型。下表列出了打包器的标准"加载器"。请参见[加载器](/bundler/loaders)。

| 扩展名                                                   | 详情                                                                                                                                         |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `.js` `.jsx` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` | 使用 Bun 的内置转译器解析文件并将 TypeScript/JSX 语法转译为普通 JavaScript。打包器执行一组默认转换，包括死代码消除和 tree shaking。Bun 不会向下转换语法；如果你使用最新的 ECMAScript 语法，它会在打包代码中原样出现。  |
| `.json`                                               | JSON 文件被解析并内联到打包产物中作为 JavaScript 对象。<br /><br />`js<br/>import pkg from "./package.json";<br/>pkg.name; // => "my-package"<br/>`           |
| `.jsonc`                                              | 带注释的 JSON。文件被解析并内联到打包产物中作为 JavaScript 对象。<br /><br />`js<br/>import config from "./config.jsonc";<br/>config.name; // => "my-config"<br/>` |
| `.toml`                                               | TOML 文件被解析并内联到打包产物中作为 JavaScript 对象。<br /><br />`js<br/>import config from "./bunfig.toml";<br/>config.logLevel; // => "debug"<br/>`       |
| `.yaml` `.yml`                                        | YAML 文件被解析并内联到打包产物中作为 JavaScript 对象。<br /><br />`js<br/>import config from "./config.yaml";<br/>config.name; // => "my-app"<br/>`          |
| `.txt`                                                | 文本文件的内容被读取并内联到打包产物中作为字符串。<br /><br />`js<br/>import contents from "./file.txt";<br/>console.log(contents); // => "Hello, world!"<br/>`     |
| `.html`                                               | HTML 文件被处理，引用的资源（脚本、样式表、图片）被打包。                                                                                                            |
| `.css`                                                | CSS 文件被打包到一起，生成输出目录中的单个 `.css` 文件。                                                                                                         |
| `.node` `.wasm`                                       | 这些文件由 Bun 运行时支持，但在打包期间它们被视为资源。                                                                                                             |

### 资源

如果打包器遇到无法识别的扩展名的导入，它会将导入的文件视为外部文件。引用的文件被原样复制到 `outdir` 中，导入被解析为文件的路径。

<CodeGroup>
  ```ts 输入 icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  // 打包入口点
  import logo from "./logo.svg";
  console.log(logo);
  ```

  ```ts 输出 icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
  // 打包后的输出
  var logo = "./logo-a7305bdef.svg";
  console.log(logo);
  ```
</CodeGroup>

文件加载器的确切行为还取决于 [`naming`](#naming) 和 [`publicPath`](#publicpath)。

<Info>关于文件加载器的更多信息，请参见[加载器](/bundler/loaders)。</Info>

### 插件

插件可以覆盖或扩展此表中描述的行为。请参见[加载器](/bundler/loaders)。

## API

### entrypoints

<Badge>必需</Badge>

对应应用入口点的路径数组。Bun 为每个入口点生成一个包。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    const result = await Bun.build({
      entrypoints: ["./index.ts"],
    });
    // => { success: boolean, outputs: BuildArtifact[], logs: BuildMessage[] }
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.ts
    ```
  </Tab>
</Tabs>

### files

一个文件路径到文件内容的映射，用于内存中打包：打包磁盘上不存在的虚拟文件，或覆盖确实存在的文件内容。此选项仅在 JavaScript API 中可用。

文件内容可以作为 `string`、`Blob`、`TypedArray` 或 `ArrayBuffer` 提供。

#### 完全从内存中打包

你可以在没有任何磁盘文件的情况下打包代码，方法是在 `files` 中提供所有源代码：

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const result = await Bun.build({
  entrypoints: ["/app/index.ts"],
  files: {
    "/app/index.ts": `
      import { greet } from "./greet.ts";
      console.log(greet("World"));
    `,
    "/app/greet.ts": `
      export function greet(name: string) {
        return "Hello, " + name + "!";
      }
    `,
  },
});

const output = await result.outputs[0].text();
console.log(output);
```

当所有入口点都在 `files` 映射中时，当前工作目录被用作根目录。

#### 覆盖磁盘上的文件

内存中的文件优先于磁盘上的文件，因此你可以在保持代码库其余部分不变的同时覆盖特定文件：

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// 假设 ./src/config.ts 存在于磁盘上，包含开发设置
await Bun.build({
  entrypoints: ["./src/index.ts"],
  files: {
    // 使用生产值覆盖 config.ts
    "./src/config.ts": `
      export const API_URL = "https://api.production.com";
      export const DEBUG = false;
    `,
  },
  outdir: "./dist",
});
```

#### 混合磁盘和虚拟文件

磁盘上的真实文件可以导入虚拟文件，虚拟文件也可以导入真实文件：

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// ./src/index.ts 存在于磁盘上，导入 "./generated.ts"
await Bun.build({
  entrypoints: ["./src/index.ts"],
  files: {
    // 提供一个 index.ts 导入的虚拟文件
    "./src/generated.ts": `
      export const BUILD_ID = "${crypto.randomUUID()}";
      export const BUILD_TIME = ${Date.now()};
    `,
  },
  outdir: "./dist",
});
```

用于代码生成、注入构建时常量或使用模拟模块进行测试。

### outdir

输出文件写入的目录。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    const result = await Bun.build({
      entrypoints: ['./index.ts'],
      outdir: './out'
    });
    // => { success: boolean, outputs: BuildArtifact[], logs: BuildMessage[] }
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.ts --outdir ./out
    ```
  </Tab>
</Tabs>

如果 JavaScript API 没有传入 `outdir`，打包后的代码不会写入磁盘。打包后的文件以 `BuildArtifact` 对象数组的形式返回。这些对象是带有额外属性的 Blob；请参见[输出](#outputs)。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const result = await Bun.build({
  entrypoints: ["./index.ts"],
});

for (const res of result.outputs) {
  // 可以作为 Blob 消费
  await res.text();

  // Bun 设置 Content-Type 和 Etag 头
  new Response(res);

  // 可以手动写入，但在此情况下应该使用 `outdir`。
  Bun.write(path.join("out", res.path), res);
}
```

当设置了 `outdir` 时，`BuildArtifact` 上的 `path` 属性是其写入的绝对路径。

### target

打包产物的预期执行环境。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.ts'],
      outdir: './out',
      target: 'browser', // 默认
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.ts --outdir ./out --target browser
    ```
  </Tab>
</Tabs>

根据目标的不同，Bun 会应用不同的模块解析规则和优化。

<Card title="browser" icon="globe">
  **默认。** 适用于在浏览器中运行的包。解析导入时优先考虑 `"browser"` 导出条件。
  导入内置模块如 `node:events` 或 `node:path` 可以工作，但调用某些函数，如 `fs.readFile`，
  则不行。
</Card>

<Card title="bun" icon="server">
  适用于在 Bun 运行时中运行的包。在许多情况下，没有必要打包服务器端代码；你可以直接执行源代码而无需修改。然而，打包你的服务器代码可以减少启动时间并提高运行性能。将此目标用于具有构建时 HTML 导入的全栈应用，其中服务器和客户端代码被打包在一起。

  所有以 `target: "bun"` 生成的包都带有 `// @bun` 编译指示，这告诉 Bun 运行时在执
  行前无需重新转译文件。

  如果任何入口点包含 Bun shebang（`#!/usr/bin/env bun`），打包器默认使用 `target: "bun"` 而不是 `"browser"`。

  当同时使用 `target: "bun"` 和 `format: "cjs"` 时，会添加 `// @bun @bun-cjs` 编译指示，并且 CommonJS 包装函数与 Node.js 不兼容。
</Card>

<Card title="node" icon="node">
  适用于在 Node.js 中运行的包。解析导入时优先考虑 `"node"` 导出条件。Bun 不会
  polyfill `Bun` 全局变量或内置的 `bun:*` 模块。
</Card>

### format

指定生成打包产物的模块格式。

Bun 默认使用 `"esm"`，并提供了对 `"cjs"` 和 `"iife"` 的实验性支持。

#### format: "esm" - ES Module

默认格式。支持 ES Module 语法，包括顶层 await 和 `import.meta`。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      format: "esm",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --format esm
    ```
  </Tab>
</Tabs>

要在浏览器中使用 ES Module 语法，将 `format` 设置为 `"esm"`，并使用 `<script type="module">` 标签加载包。

#### format: "cjs" - CommonJS

要构建 CommonJS 模块，将 `format` 设置为 `"cjs"`。选择 `"cjs"` 时，默认目标从 `"browser"`（esm）变为 `"node"`（cjs）。使用 `format: "cjs"`、`target: "node"` 转译的 CommonJS 模块在 Bun 和 Node.js 中都运行（假设使用的 API 两者都支持）。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      format: "cjs",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --format cjs
    ```
  </Tab>
</Tabs>

#### format: "iife" - IIFE

TODO：在支持 globalNames 后记录 IIFE。

### `jsx`

配置 JSX 的编译方式。

**经典运行时示例**（使用 `factory` 和 `fragment`）：

<CodeGroup>
  ```ts index.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  await Bun.build({
    entrypoints: ["./app.tsx"],
    outdir: "./out",
    jsx: {
      factory: "h",
      fragment: "Fragment",
      runtime: "classic",
    },
  });
  ```

  ```bash terminal icon="terminal" theme={null}
  # JSX 配置通过 bunfig.toml 或 tsconfig.json 处理
  bun build ./app.tsx --outdir ./out
  ```
</CodeGroup>

**自动运行时示例**（使用 `importSource`）：

<CodeGroup>
  ```ts index.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  await Bun.build({
    entrypoints: ["./app.tsx"],
    outdir: "./out",
    jsx: {
      importSource: "preact",
      runtime: "automatic",
    },
  });
  ```

  ```bash terminal icon="terminal" theme={null}
  # JSX 配置通过 bunfig.toml 或 tsconfig.json 处理
  bun build ./app.tsx --outdir ./out
  ```
</CodeGroup>

### splitting

是否启用代码分割。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      splitting: false, // 默认
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --splitting
    ```
  </Tab>
</Tabs>

当为 `true` 时，打包器启用代码分割。当多个入口点导入相同的文件或模块时，打包器可以将共享代码分割为单独的包，称为**块**。考虑以下文件：

<CodeGroup>
  ```ts entry-a.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  import { shared } from "./shared.ts";
  ```

  ```ts entry-b.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  import { shared } from "./shared.ts";
  ```

  ```ts shared.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  export const shared = "shared";
  ```
</CodeGroup>

要打包启用了代码分割的 `entry-a.ts` 和 `entry-b.ts`：

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./entry-a.ts', './entry-b.ts'],
      outdir: './out',
      splitting: true,
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./entry-a.ts ./entry-b.ts --outdir ./out --splitting
    ```
  </Tab>
</Tabs>

运行此构建会生成以下文件：

```text title="file system" icon="folder-tree" theme={null}
.
├── entry-a.tsx
├── entry-b.tsx
├── shared.tsx
└── out
    ├── entry-a.js
    ├── entry-b.js
    └── chunk-2fce6291bf86559d.js
```

生成的 `chunk-2fce6291bf86559d.js` 文件包含共享代码。为避免冲突，文件名默认包含内容哈希。使用 [`naming`](#naming) 自定义。

### plugins

在打包期间使用的插件列表。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
await Bun.build({
  entrypoints: ["./index.tsx"],
  outdir: "./out",
  plugins: [
    /* ... */
  ],
});
```

Bun 的插件系统由运行时和打包器共享。请参见[插件](/bundler/plugins)。

### env

控制打包期间环境变量的处理方式。内部使用 `define` 将环境变量注入打包产物；`env` 是指定哪些变量的简写。

#### env: "inline"

通过将 `process.env.FOO` 引用转换为包含实际环境变量值的字符串字面量，将环境变量注入打包输出。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      env: "inline",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --env inline
    ```
  </Tab>
</Tabs>

对于以下输入：

```js title="input.js" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
// input.js
console.log(process.env.FOO);
console.log(process.env.BAZ);
```

生成的包包含以下代码：

```js title="output.js" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
// output.js
console.log("bar");
console.log("123");
```

#### env: "PUBLIC\_\*"（前缀）

内联匹配给定前缀（`*` 字符之前的部分）的环境变量，将 `process.env.FOO` 替换为实际的环境变量值。使用前缀可只内联公共值，如面向外部的 URL 或客户端令牌，而无需将私有凭据注入输出包中。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      
      // 内联所有以 "ACME_PUBLIC_" 开头的环境变量
      env: "ACME_PUBLIC_*",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --env ACME_PUBLIC_*
    ```
  </Tab>
</Tabs>

例如，给定以下环境变量：

```bash terminal icon="terminal" theme={null}
FOO=bar BAZ=123 ACME_PUBLIC_URL=https://acme.com
```

以及源代码：

```tsx index.tsx icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
console.log(process.env.FOO);
console.log(process.env.ACME_PUBLIC_URL);
console.log(process.env.BAZ);
```

生成的包包含以下代码：

```js title="output.js" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
console.log(process.env.FOO);
console.log("https://acme.com");
console.log(process.env.BAZ);
```

#### env: "disable"

完全禁用环境变量注入。

### sourcemap

指定生成的 sourcemap 类型。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      sourcemap: 'linked', // 默认 'none'
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --sourcemap linked
    ```
  </Tab>
</Tabs>

| 值            | 描述                                                                                                                                                                                                                  |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"none"`     | 默认。不生成 sourcemap。                                                                                                                                                                                                   |
| `"linked"`   | 在每个 `*.js` 包旁创建一个单独的 `*.js.map` 文件，使用 `//# sourceMappingURL` 注释将两者关联。需要设置 `--outdir`。其基础 URL 可以通过 `--public-path` 自定义。<br /><br />`js<br/>// <打包后的代码><br/><br/>//# sourceMappingURL=bundle.js.map<br/>`             |
| `"external"` | 在每个 `*.js` 包旁创建一个单独的 `*.js.map` 文件，但不插入 `//# sourceMappingURL` 注释。<br /><br />生成的包包含一个调试 ID，可用于将包与其对应的 sourcemap 关联起来。此 `debugId` 作为注释添加到文件底部。<br /><br />`js<br/>// <生成的包代码><br/><br/>//# debugId=<DEBUG ID><br/>` |
| `"inline"`   | 生成 sourcemap 并作为 base64 载荷附加到生成的包末尾。<br /><br />`js<br/>// <打包后的代码><br/><br/>//# sourceMappingURL=data:application/json;base64,<编码后的 sourcemap><br/>`                                                               |

相关的 `*.js.map` sourcemap 是一个 JSON 文件，包含等效的 `debugId` 属性。

### minify

是否启用压缩。默认为 `false`。

要启用所有压缩选项：

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      minify: true, // 默认 false
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --minify
    ```
  </Tab>
</Tabs>

要精细启用某些压缩：

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      minify: {
        whitespace: true,
        identifiers: true,
        syntax: true,
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --minify-whitespace --minify-identifiers --minify-syntax
    ```
  </Tab>
</Tabs>

### external

要视为外部的导入路径列表。默认为 `[]`。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      external: ["lodash", "react"], // 默认：[]
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --external lodash --external react
    ```
  </Tab>
</Tabs>

外部导入不会包含在最终包中。相反，导入语句原样保留，在运行时解析。

例如，考虑以下入口点文件：

```tsx index.tsx icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import _ from "lodash";
import { z } from "zod";

const value = z.string().parse("Hello world!");
console.log(_.upperCase(value));
```

通常，打包 `index.tsx` 会生成包含 "zod" 包完整源代码的包。要原样保留导入语句，将其标记为外部：

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      external: ['zod'],
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --external zod
    ```
  </Tab>
</Tabs>

生成的包看起来像这样：

```js title="out/index.js" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
import { z } from "zod";

// ...
// "lodash" 包的内容
// 包括 `_.upperCase` 函数

var value = z.string().parse("Hello world!");
console.log(_.upperCase(value));
```

要将所有导入标记为外部，使用通配符 `*`：

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      external: ['*'],
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --external '*'
    ```
  </Tab>
</Tabs>

### packages

控制是否在包中包含包依赖项。可能的值：`bundle`（默认）、`external`。Bun 将任何路径不以 `.`、`..` 或 `/` 开头的导入视为包。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.ts'],
      packages: 'external',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.ts --packages external
    ```
  </Tab>
</Tabs>

### naming

自定义生成的文件名。默认为 `./[dir]/[name].[ext]`。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      naming: "[dir]/[name].[ext]", // 默认
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --entry-naming "[dir]/[name].[ext]"
    ```
  </Tab>
</Tabs>

默认情况下，生成的包名称基于关联入口点的名称。

```text title="file system" icon="folder-tree" theme={null}
.
├── index.tsx
└── out
    └── index.js
```

对于多个入口点，生成的文件层次结构反映入口点的目录结构。

```text title="file system" icon="folder-tree" theme={null}
.
├── index.tsx
└── nested
    └── index.tsx
└── out
    ├── index.js
    └── nested
        └── index.js
```

`naming` 字段自定义生成文件的名称和位置。它接受一个模板字符串，用于所有对应入口点的包，其中以下令牌被替换为其值：

* `[name]` - 入口点文件的名称，不带扩展名。
* `[ext]` - 生成包的扩展名。
* `[hash]` - 包内容的哈希值。
* `[dir]` - 从项目根目录到源文件父目录的相对路径。

例如：

| 令牌                  | `[name]` | `[ext]` | `[hash]`   | `[dir]`    |
| ------------------- | -------- | ------- | ---------- | ---------- |
| `./index.tsx`       | `index`  | `js`    | `a1b2c3d4` | `""`（空字符串） |
| `./nested/entry.ts` | `entry`  | `js`    | `c3d4e5f6` | `"nested"` |

组合这些令牌以创建模板字符串。例如，在生成的包名称中包含哈希：

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      naming: 'files/[dir]/[name]-[hash].[ext]',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --entry-naming 'files/[dir]/[name]-[hash].[ext]'
    ```
  </Tab>
</Tabs>

此构建将产生以下文件结构：

```text title="file system" icon="folder-tree" theme={null}
.
├── index.tsx
└── out
    └── files
        └── index-a1b2c3d4.js
```

当为 `naming` 字段提供字符串时，仅用于对应入口点的包。块和复制资源的名称不受影响。在 JavaScript API 中，你可以为每种类型的生成文件指定单独的模板字符串。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      naming: {
        // 默认值
        entry: '[dir]/[name].[ext]',
        chunk: '[name]-[hash].[ext]',
        asset: '[name]-[hash].[ext]',
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out \
      --entry-naming '[dir]/[name].[ext]' \
      --chunk-naming '[name]-[hash].[ext]' \
      --asset-naming '[name]-[hash].[ext]'
    ```
  </Tab>
</Tabs>

### root

项目的根目录。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./pages/a.tsx', './pages/b.tsx'],
      outdir: './out',
      root: '.',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./pages/a.tsx ./pages/b.tsx --outdir ./out --root .
    ```
  </Tab>
</Tabs>

如果未指定，它会计算为所有入口点文件的第一个公共祖先。考虑以下文件结构：

```text title="file system" icon="folder-tree" theme={null}
.
└── pages
  └── index.tsx
  └── settings.tsx
```

构建 `pages` 目录中的两个入口点：

<Tabs>
  <Tab title="JavaScript">
    ```js theme={null}
    await Bun.build({
      entrypoints: ['./pages/index.tsx', './pages/settings.tsx'],
      outdir: './out',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    bun build ./pages/index.tsx ./pages/settings.tsx --outdir ./out
    ```
  </Tab>
</Tabs>

这将产生如下文件结构：

```text title="file system" icon="folder-tree" theme={null}
.
└── pages
  └── index.tsx
  └── settings.tsx
└── out
  └── index.js
  └── settings.js
```

由于 `pages` 目录是入口点文件的第一个公共祖先，它被视为项目根目录，因此生成的包位于 `out` 目录的顶层；没有 `out/pages` 目录。

通过指定 `root` 选项覆盖此行为：

<Tabs>
  <Tab title="JavaScript">
    ```js theme={null}
    await Bun.build({
      entrypoints: ['./pages/index.tsx', './pages/settings.tsx'],
      outdir: './out',
      root: '.',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    bun build ./pages/index.tsx ./pages/settings.tsx --outdir ./out --root .
    ```
  </Tab>
</Tabs>

以 `.` 为 `root`，生成的文件结构如下：

```
.
└── pages
  └── index.tsx
  └── settings.tsx
└── out
  └── pages
    └── index.js
    └── settings.js
```

### publicPath

添加到打包代码中任何导入路径的前缀。

在许多情况下，生成的包不包含导入语句；打包的目标是将所有代码合并到一个文件中。然而，在少数情况下，生成的包确实包含导入语句：

* **资源导入** — 当导入无法识别的文件类型如 `*.svg` 时，打包器委托文件加载器处理，该加载器将文件原样复制到 `outdir` 中。导入被转换为变量。
* **外部模块** — 标记为外部的文件和模块不会包含在包中。相反，导入语句保留在最终包中。
* **分块**。当启用 `splitting` 时，打包器可能会生成代表多个入口点间共享代码的单独"块"文件。

在任何这些情况下，最终包可能包含指向其他文件的路径。默认情况下，这些导入是相对的。以下是一个资源导入的示例：

<CodeGroup>
  ```ts 输入 icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  import logo from "./logo.svg";
  console.log(logo);
  ```

  ```ts 输出 icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
  var logo = "./logo-a7305bdef.svg";
  console.log(logo);
  ```
</CodeGroup>

设置 `publicPath` 会为所有文件路径添加指定值作为前缀。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      publicPath: 'https://cdn.example.com/', // 默认为 undefined
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --public-path 'https://cdn.example.com/'
    ```
  </Tab>
</Tabs>

输出文件现在看起来像这样：

```js title="out/index.js" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
var logo = "https://cdn.example.com/logo-a7305bdef.svg";
```

### define

要在构建时替换的全局标识符映射。此对象的键是标识符名称，值是内联的 JSON 字符串。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      define: {
        STRING: JSON.stringify("value"),
        "nested.boolean": "true",
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --define STRING='"value"' --define nested.boolean=true
    ```
  </Tab>
</Tabs>

### loader

文件扩展到内置加载器名称的映射。用于自定义某些文件的加载方式。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      loader: {
        ".png": "dataurl",
        ".txt": "file",
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --loader .png:dataurl --loader .txt:file
    ```
  </Tab>
</Tabs>

### banner

添加到最终包的 banner。可以是像 React 的 `"use client"` 这样的指令，或像许可证这样的注释块。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      banner: '"use client";'
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --banner '"use client";'
    ```
  </Tab>
</Tabs>

### footer

添加到最终包的 footer。可以是许可证的注释块或有趣的彩蛋。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      footer: '// built with love in SF'
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --footer '// built with love in SF'
    ```
  </Tab>
</Tabs>

### drop

从包中移除函数调用。例如，`--drop=console` 移除对 `console.log` 的所有调用。被丢弃调用的参数也会被移除，即使它们有副作用。丢弃 `debugger` 会移除所有 `debugger` 语句。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      drop: ["console", "debugger", "anyIdentifier.or.propertyAccess"],
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./index.tsx --outdir ./out --drop console --drop debugger
    ```
  </Tab>
</Tabs>

### features

为死代码消除启用编译时特性标志：使用 `import { feature } from "bun:bundle"` 在打包时有条件地包含或排除代码路径。

```ts title="app.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { feature } from "bun:bundle";

if (feature("PREMIUM")) {
  // 仅在启用 PREMIUM 标志时包含
  initPremiumFeatures();
}

if (feature("DEBUG")) {
  // 仅在启用 DEBUG 标志时包含
  console.log("Debug 模式");
}
```

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    await Bun.build({
      entrypoints: ['./app.ts'],
      outdir: './out',
      features: ["PREMIUM"],  // PREMIUM=true, DEBUG=false
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./app.ts --outdir ./out --feature PREMIUM
    ```
  </Tab>
</Tabs>

`feature()` 函数在打包时被替换为 `true` 或 `false`。结合压缩，不可达代码被消除：

```ts title="输入" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { feature } from "bun:bundle";
const mode = feature("PREMIUM") ? "premium" : "free";
```

```js title="输出（带 --feature PREMIUM --minify）" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
var mode = "premium";
```

```js title="输出（不带 --feature PREMIUM，带 --minify）" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
var mode = "free";
```

**关键行为：**

* `feature()` 需要字符串字面量参数——不支持动态值
* `bun:bundle` 导入完全从输出中移除
* 适用于 `bun build`、`bun run` 和 `bun test`
* 多个标志可以同时启用：`--feature FLAG_A --feature FLAG_B`
* 对于类型安全，扩展 `Registry` 接口以将 `feature()` 限制为已知标志

**用例：**

* 平台特定代码（`feature("SERVER")` vs `feature("CLIENT")`）
* 基于环境的功能（`feature("DEVELOPMENT")`）
* 渐进式功能发布
* A/B 测试变体
* 付费层级功能

**类型安全：** 默认情况下，`feature()` 接受任何字符串。要获得自动补全并在编译时捕获拼写错误，创建一个 `env.d.ts` 文件（或添加到现有的 `.d.ts`）并扩展 `Registry` 接口：

```ts title="env.d.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
declare module "bun:bundle" {
  interface Registry {
    features: "DEBUG" | "PREMIUM" | "BETA_FEATURES";
  }
}
```

确保该文件包含在你的 `tsconfig.json` 中（例如，`"include": ["src", "env.d.ts"]`）。现在 `feature()` 只接受这些标志，像 `feature("TYPO")` 这样的无效字符串会变成类型错误。

### optimizeImports

跳过对 barrel 文件（重新导出的索引文件）中未使用子模块的解析。当你从大型库中只导入少量命名导出时，通常打包器会解析 barrel 重新导出的每个文件。使用 `optimizeImports`，只解析你使用的子模块。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
await Bun.build({
  entrypoints: ["./app.ts"],
  outdir: "./out",
  optimizeImports: ["antd", "@mui/material", "lodash-es"],
});
```

例如，`import { Button } from 'antd'` 通常会解析 `antd/index.js` 重新导出的所有约 3000 个模块。使用 `optimizeImports: ['antd']`，只解析 `Button` 子模块。

这适用于**纯 barrel 文件**——每个命名导出都是重新导出的文件（`export { X } from './x'`）。如果 barrel 文件有任何本地导出（`export const foo = ...`），或者任何导入者使用 `import *`，所有子模块都会被加载。

`export *` 重新导出总是被加载（从不延迟）以避免循环解析问题。只有不被任何导入者使用的命名重新导出（`export { X } from './x'`）会被延迟。

**自动模式：** 在 `package.json` 中带有 `"sideEffects": false` 的包会自动获得 barrel 优化——无需配置 `optimizeImports`。对于没有此字段的包，使用 `optimizeImports`。

**插件：** Resolve 和 load 插件与 barrel 优化一起工作。延迟的子模块在最终加载时会经过插件流水线。

### metafile

以结构化格式生成关于构建的元数据。元数据描述每个输入和输出文件：大小、导入和导出。用于：

* **包分析**：了解哪些内容对包体积有贡献
* **可视化**：输入到 [esbuild 的包分析器](https://esbuild.github.io/analyze/)等工具
* **依赖跟踪**：查看应用程序的完整导入图
* **CI 集成**：跟踪包体积随时间的变化

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    const result = await Bun.build({
      entrypoints: ['./src/index.ts'],
      outdir: './dist',
      metafile: true,
    });

    if (result.metafile) {
      // 分析输入
      for (const [path, meta] of Object.entries(result.metafile.inputs)) {
        console.log(`${path}: ${meta.bytes} 字节`);
      }

      // 分析输出
      for (const [path, meta] of Object.entries(result.metafile.outputs)) {
        console.log(`${path}: ${meta.bytes} 字节`);
      }

      // 保存到外部分析工具
      await Bun.write('./dist/meta.json', JSON.stringify(result.metafile));
    }
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./src/index.ts --outdir ./dist --metafile ./dist/meta.json
    ```
  </Tab>
</Tabs>

#### Markdown 元数据文件

使用 `--metafile-md` 生成 markdown 格式的元数据文件，对 LLM 友好，终端可读：

```bash terminal icon="terminal" theme={null}
bun build ./src/index.ts --outdir ./dist --metafile-md ./dist/meta.md
```

`--metafile` 和 `--metafile-md` 可以同时使用：

```bash terminal icon="terminal" theme={null}
bun build ./src/index.ts --outdir ./dist --metafile ./dist/meta.json --metafile-md ./dist/meta.md
```

#### `metafile` 选项格式

在 JavaScript API 中，`metafile` 接受多种形式：

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// 布尔值 —— 在结果对象中包含 metafile
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  metafile: true,
});

// 字符串 —— 将 JSON metafile 写入特定路径
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  metafile: "./dist/meta.json",
});

// 对象 —— 分别为 JSON 和 markdown 输出指定路径
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  metafile: {
    json: "./dist/meta.json",
    markdown: "./dist/meta.md",
  },
});
```

元数据结构包含：

```ts theme={null}
interface BuildMetafile {
  inputs: {
    [path: string]: {
      bytes: number;
      imports: Array<{
        path: string;
        kind: ImportKind;
        original?: string; // 解析前的原始标识符
        external?: boolean;
      }>;
      format?: "esm" | "cjs" | "json" | "css";
    };
  };
  outputs: {
    [path: string]: {
      bytes: number;
      inputs: {
        [path: string]: { bytesInOutput: number };
      };
      imports: Array<{ path: string; kind: ImportKind }>;
      exports: string[];
      entryPoint?: string;
      cssBundle?: string; // JS 入口点关联的 CSS 文件
    };
  };
}
```

## 输出

`Bun.build` 函数返回一个 `Promise<BuildOutput>`，定义如下：

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<object>; // 详情请见文档
  metafile?: BuildMetafile; // 仅在 metafile: true 时可用
}

interface BuildArtifact extends Blob {
  kind: "entry-point" | "chunk" | "asset" | "sourcemap" | "bytecode";
  path: string;
  loader: Loader;
  hash: string | null;
  sourcemap: BuildArtifact | null;
}
```

`outputs` 数组包含构建生成的所有文件。每个 artifact 都实现了 Blob 接口。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const build = await Bun.build({
  /* */
});

for (const output of build.outputs) {
  await output.arrayBuffer(); // => ArrayBuffer
  await output.bytes(); // => Uint8Array
  await output.text(); // string
}
```

每个 artifact 还包含以下属性：

| 属性          | 描述                                                                |
| ----------- | ----------------------------------------------------------------- |
| `kind`      | 此文件是何种构建输出。构建会生成打包后的入口点、代码分割"块"、sourcemap、字节码和复制的资源（如图片）。         |
| `path`      | 文件在磁盘上的绝对路径                                                       |
| `loader`    | 用于解释文件的加载器。有关 Bun 如何将文件扩展名映射到内置加载器的信息，请参见[加载器](/bundler/loaders)。 |
| `hash`      | 文件内容的哈希值。对于资源始终定义。                                                |
| `sourcemap` | 与此文件对应的 sourcemap 文件（如果生成）。仅对入口点和块定义。                             |

与 `BunFile` 类似，`BuildArtifact` 对象可以直接传递给 `new Response()`。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const build = await Bun.build({
  /* */
});

const artifact = build.outputs[0];

// Content-Type 头自动设置
return new Response(artifact);
```

Bun 运行时漂亮地打印 `BuildArtifact` 对象以简化调试。

<CodeGroup>
  ```ts build.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
  // build.ts
  const build = await Bun.build({
    /* */
  });

  const artifact = build.outputs[0];
  console.log(artifact);
  ```

  ```bash Shell 输出 theme={null}
  bun run build.ts

  BuildArtifact (entry-point) {
    path: "./index.js",
    loader: "tsx",
    kind: "entry-point",
    hash: "824a039620219640",
    Blob (74756 bytes) {
      type: "text/javascript;charset=utf-8"
    },
    sourcemap: BuildArtifact (sourcemap) {
      path: "./index.js.map",
      loader: "file",
      kind: "sourcemap",
      hash: "e7178cda3e72e301",
      Blob (24765 bytes) {
        type: "application/json;charset=utf-8"
      },
      sourcemap: null
    }
  }
  ```
</CodeGroup>

## 字节码

`bytecode: boolean` 选项为任何 JavaScript/TypeScript 入口点生成字节码，这可以大大改善大型应用的启动时间。需要 `"target": "bun"` 和匹配的 Bun 版本。

* **CommonJS**：可以使用或不使用 `compile: true`。在每个入口点旁边生成一个 `.jsc` 文件。
* **ESM**：需要 `compile: true`。字节码和模块元数据嵌入到独立可执行文件中。

没有显式的 `format` 时，字节码默认为 CommonJS。

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    // CommonJS 字节码（生成 .jsc 文件）
    await Bun.build({
      entrypoints: ["./index.tsx"],
      outdir: "./out",
      bytecode: true,
    })

    // ESM 字节码（需要 compile）
    await Bun.build({
      entrypoints: ["./index.tsx"],
      outfile: "./mycli",
      bytecode: true,
      format: "esm",
      compile: true,
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    # CommonJS 字节码
    bun build ./index.tsx --outdir ./out --bytecode

    # ESM 字节码（需要 --compile）
    bun build ./index.tsx --outfile ./mycli --bytecode --format=esm --compile
    ```
  </Tab>
</Tabs>

## 可执行文件

Bun 支持将 JavaScript/TypeScript 入口点"编译"为独立可执行文件。此可执行文件包含一份 Bun 二进制文件的副本。

```bash terminal icon="terminal" theme={null}
bun build ./cli.tsx --outfile mycli --compile
./mycli
```

请参见[独立可执行文件](/bundler/executables)。

## 日志和错误

失败时，`Bun.build` 返回一个带有 `AggregateError` 的 rejected promise。将其记录到控制台以漂亮打印错误列表，或使用 try/catch 块以编程方式读取。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
try {
  const result = await Bun.build({
    entrypoints: ["./index.tsx"],
    outdir: "./out",
  });
} catch (e) {
  // TypeScript 不允许在 catch 子句上使用类型注解
  const error = e as AggregateError;
  console.error("构建失败");

  // 示例：使用内置格式化器
  console.error(error);

  // 示例：将失败序列化为 JSON 字符串。
  console.error(JSON.stringify(error, null, 2));
}
```

大多数时候，不需要显式的 try/catch，因为 Bun 会打印未捕获的异常。你可以在 `Bun.build` 调用上使用顶层 await。

`error.errors` 中的每个项都是 `BuildMessage` 或 `ResolveMessage`（`Error` 的子类）的实例，包含每个错误的详细信息。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
class BuildMessage {
  name: string;
  position?: Position;
  message: string;
  level: "error" | "warning" | "info" | "debug" | "verbose";
}

class ResolveMessage extends BuildMessage {
  code: string;
  referrer: string;
  specifier: string;
  importKind: ImportKind;
}
```

构建成功时，返回的对象包含一个 `logs` 属性，其中包含打包器的警告和信息消息。

```ts title="build.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const result = await Bun.build({
  entrypoints: ["./index.tsx"],
  outdir: "./out",
});

if (result.logs.length > 0) {
  console.warn("构建成功，但有警告：");
  for (const message of result.logs) {
    // Bun 对消息对象进行漂亮打印
    console.warn(message);
  }
}
```

## 参考

```ts TypeScript 定义 icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" expandable theme={null}
interface Bun {
  build(options: BuildOptions): Promise<BuildOutput>;
}

interface BuildConfig {
  entrypoints: string[]; // 文件路径列表
  outdir?: string; // 输出目录
  target?: Target; // 默认："browser"
  /**
   * 输出模块格式。仅 `"esm"` 支持顶层 await。
   *
   * 可以为：
   * - `"esm"`
   * - `"cjs"`（**实验性**）
   * - `"iife"`（**实验性**）
   *
   * @default "esm"
   */
  format?: "esm" | "cjs" | "iife";
  /**
   * JSX 配置对象，用于控制 JSX 转换行为
   */
  jsx?: {
    runtime?: "automatic" | "classic";
    importSource?: string;
    factory?: string;
    fragment?: string;
    sideEffects?: boolean;
    development?: boolean;
  };
  naming?:
    | string
    | {
        chunk?: string;
        entry?: string;
        asset?: string;
      };
  root?: string; // 项目根目录
  splitting?: boolean; // 默认 false，启用代码分割
  plugins?: BunPlugin[];
  external?: string[];
  packages?: "bundle" | "external";
  publicPath?: string;
  define?: Record<string, string>;
  loader?: { [k in string]: Loader };
  sourcemap?: "none" | "linked" | "inline" | "external" | boolean; // 默认："none", true -> "inline"
  /**
   * 解析导入时使用的 package.json `exports` 条件
   *
   * 等同于 `bun build` 或 `bun run` 中的 `--conditions`。
   *
   * https://nodejs.org/api/packages.html#exports
   */
  conditions?: Array<string> | string;

  /**
   * 控制打包期间环境变量的处理方式。
   *
   * 可以为：
   * - `"inline"`：通过将 `process.env.FOO` 引用转换为包含实际环境变量值的字符串字面量，将环境变量注入打包输出
   * - `"disable"`：完全禁用环境变量注入
   * - 以 `*` 结尾的字符串：内联匹配给定前缀的环境变量。
   *   例如，`"MY_PUBLIC_*"` 只会包含以 "MY_PUBLIC_" 开头的环境变量
   */
  env?: "inline" | "disable" | `${string}*`;
  minify?:
    | boolean
    | {
        whitespace?: boolean;
        syntax?: boolean;
        identifiers?: boolean;
      };
  /**
   * 忽略死代码消除/tree-shaking 注解，如 @__PURE__ 和 package.json
   * "sideEffects" 字段。仅应作为库中不正确注解的临时解决方法使用。
   */
  ignoreDCEAnnotations?: boolean;
  /**
   * 即使 minify.whitespace 为 true，也强制发出 @__PURE__ 注解。
   */
  emitDCEAnnotations?: boolean;

  /**
   * 为输出生成字节码。这可以显著改善冷启动
   * 时间，但会使最终输出更大并略微增加
   * 内存使用。
   *
   * - CommonJS：可以使用或不使用 `compile: true`
   * - ESM：需要 `compile: true`
   *
   * 没有显式的 `format` 时，默认为 CommonJS。
   *
   * 必须为 `target: "bun"`
   * @default false
   */
  bytecode?: boolean;
  /**
   * 向打包代码添加 banner，例如 "use client";
   */
  banner?: string;
  /**
   * 向打包代码添加 footer，例如注释块
   *
   * `// made with bun!`
   */
  footer?: string;

  /**
   * 丢弃匹配属性访问的函数调用。
   */
  drop?: string[];

  /**
   * - 设置为 `true` 时，当构建失败时返回的 promise 会以 AggregateError 拒绝。
   * - 设置为 `false` 时，返回带有 `{success: false}` 的 {@link BuildOutput}
   *
   * @default true
   */
  throw?: boolean;

  /**
   * 用于路径解析的自定义 tsconfig.json 文件路径。
   * 等同于 CLI 中的 `--tsconfig-override`。
   */
  tsconfig?: string;

  outdir?: string;
}

interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<BuildMessage | ResolveMessage>;
}

interface BuildArtifact extends Blob {
  path: string;
  loader: Loader;
  hash: string | null;
  kind: "entry-point" | "chunk" | "asset" | "sourcemap" | "bytecode";
  sourcemap: BuildArtifact | null;
}

type Loader =
  | "js"
  | "jsx"
  | "ts"
  | "tsx"
  | "css"
  | "json"
  | "jsonc"
  | "toml"
  | "yaml"
  | "text"
  | "file"
  | "napi"
  | "wasm"
  | "html";

interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<BuildMessage | ResolveMessage>;
}

declare class ResolveMessage {
  readonly name: "ResolveMessage";
  readonly position: Position | null;
  readonly code: string;
  readonly message: string;
  readonly referrer: string;
  readonly specifier: string;
  readonly importKind:
    | "entry_point"
    | "stmt"
    | "require"
    | "import"
    | "dynamic"
    | "require_resolve"
    | "at"
    | "at_conditional"
    | "url"
    | "internal";
  readonly level: "error" | "warning" | "info" | "debug" | "verbose";

  toString(): string;
}
```

***

## CLI 用法

```bash theme={null}
bun build <entry points>
```

### 通用配置

<ParamField path="--production" type="boolean">
  设置 <code>NODE\_ENV=production</code> 并启用压缩
</ParamField>

<ParamField path="--bytecode" type="boolean">
  编译时使用字节码缓存
</ParamField>

<ParamField path="--target" type="string" default="browser">
  打包的预期执行环境。可选：<code>browser</code>、<code>bun</code> 或 <code>node</code>
</ParamField>

<ParamField path="--conditions" type="string">
  传递自定义解析条件
</ParamField>

<ParamField path="--env" type="string" default="disable">
  将环境变量内联到打包文件中，作为 <code>process.env.\${name_0}</code>。要内联匹配前缀的变量，使用类似 <code>FOO\_PUBLIC\_\*</code> 的 glob
</ParamField>

### 输出与文件处理

<ParamField path="--outdir" type="string" default="dist">
  输出目录（构建多个入口点时使用）
</ParamField>

<ParamField path="--outfile" type="string">
  将输出写入特定文件
</ParamField>

<ParamField path="--sourcemap" type="string" default="none">
  生成 source map。可选：<code>linked</code>、<code>inline</code>、<code>external</code> 或 <code>none</code>
</ParamField>

<ParamField path="--banner" type="string">
  在输出中添加横幅（例如 React Server Components 的 <code>"use client"</code>）
</ParamField>

<ParamField path="--footer" type="string">
  在输出中添加页脚（例如 <code>// built with bun!</code>）
</ParamField>

<ParamField path="--format" type="string" default="esm">
  输出包的模块格式。可选：<code>esm</code>、<code>cjs</code> 或 <code>iife</code>。使用 <code>--bytecode</code> 时默认为 <code>cjs</code>
</ParamField>

### 文件命名

<ParamField path="--entry-naming" type="string" default="[dir]/[name].[ext]">
  自定义入口点文件名
</ParamField>

<ParamField path="--chunk-naming" type="string" default="[name]-[hash].[ext]">
  自定义代码块文件名
</ParamField>

<ParamField path="--asset-naming" type="string" default="[name]-[hash].[ext]">
  自定义资源文件名
</ParamField>

### 打包选项

<ParamField path="--root" type="string">
  打包多个入口点时使用的根目录
</ParamField>

<ParamField path="--splitting" type="boolean">
  为共享模块启用代码分割
</ParamField>

<ParamField path="--public-path" type="string">
  添加到打包代码中导入路径的前缀
</ParamField>

<ParamField path="--external" type="string">
  从打包中排除模块（支持通配符）。别名：<code>-e</code>
</ParamField>

<ParamField path="--packages" type="string" default="bundle">
  如何处理依赖：<code>external</code> 或 <code>bundle</code>
</ParamField>

<ParamField path="--no-bundle" type="boolean">
  仅转译——不打包
</ParamField>

<ParamField path="--css-chunking" type="boolean">
  将 CSS 文件合并打包以减少重复（仅在多个入口点导入 CSS 时）
</ParamField>

### 压缩与优化

<ParamField path="--emit-dce-annotations" type="boolean" default="true">
  重新发出死代码消除注解。使用 <code>--minify-whitespace</code> 时禁用
</ParamField>

<ParamField path="--minify" type="boolean">
  启用所有压缩选项
</ParamField>

<ParamField path="--minify-syntax" type="boolean">
  压缩语法和内联常量
</ParamField>

<ParamField path="--minify-whitespace" type="boolean">
  压缩空白
</ParamField>

<ParamField path="--minify-identifiers" type="boolean">
  压缩变量和函数标识符
</ParamField>

<ParamField path="--keep-names" type="boolean">
  压缩时保留原始函数和类名
</ParamField>

### 开发功能

<ParamField path="--watch" type="boolean">
  文件变化时自动重新构建
</ParamField>

<ParamField path="--no-clear-screen" type="boolean">
  使用 <code>--watch</code> 重新构建时不清除终端屏幕
</ParamField>

<ParamField path="--react-fast-refresh" type="boolean">
  启用 React Fast Refresh 转换（用于开发测试）
</ParamField>

<ParamField path="--react-compiler" type="boolean">
  在 <code>.jsx</code>/<code>.tsx</code> 文件上运行 React Compiler，自动记忆组件和钩子。输出模式由 <code>--target</code> 决定（<code>browser</code> → 客户端，<code>bun</code>/<code>node</code> → ssr）。实验性功能。
</ParamField>

### 独立可执行文件

<ParamField path="--compile" type="boolean">
  生成包含打包文件的独立 Bun 可执行文件
</ParamField>

<ParamField path="--compile-exec-argv" type="string">
  将参数预先附加到独立可执行文件的 <code>execArgv</code>
</ParamField>

### Windows 可执行文件详情

<ParamField path="--windows-hide-console" type="boolean">
  运行编译后的 Windows 可执行文件时阻止控制台窗口打开
</ParamField>

<ParamField path="--windows-icon" type="string">
  设置 Windows 可执行文件的图标
</ParamField>

<ParamField path="--windows-title" type="string">
  设置 Windows 可执行文件的产品名称
</ParamField>

<ParamField path="--windows-publisher" type="string">
  设置 Windows 可执行文件的公司名称
</ParamField>

<ParamField path="--windows-version" type="string">
  设置 Windows 可执行文件的版本（例如 <code>1.2.3.4</code>）
</ParamField>

<ParamField path="--windows-description" type="string">
  设置 Windows 可执行文件的描述
</ParamField>

<ParamField path="--windows-copyright" type="string">
  设置 Windows 可执行文件的版权声明
</ParamField>

### 实验性与应用构建

<ParamField path="--app" type="boolean">
  <b>（实验性）</b>使用 Bun Bake 构建生产版 Web 应用
</ParamField>

<ParamField path="--server-components" type="boolean">
  <b>（实验性）</b>启用 React Server Components
</ParamField>

<ParamField path="--debug-dump-server-files" type="boolean">
  当设置了 <code>--app</code> 时，即使在静态构建中也将所有服务端文件转储到磁盘
</ParamField>

<ParamField path="--debug-no-minify" type="boolean">
  当设置了 <code>--app</code> 时，禁用所有压缩
</ParamField>
