> ## 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 从 TypeScript 或 JavaScript 文件生成独立可执行文件

Bun 的打包器实现了 `--compile` 标志，用于从 TypeScript 或 JavaScript 文件生成独立的二进制文件。

<Tabs>
  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build ./cli.ts --compile --outfile mycli
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./cli.ts"],
      compile: {
        outfile: "./mycli",
      },
    });
    ```
  </Tab>
</Tabs>

```ts cli.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
console.log("Hello world!");
```

这将 `cli.ts` 打包成一个你可以直接运行的可执行文件：

```bash terminal icon="terminal" theme={null}
./mycli
```

```txt theme={null}
Hello world!
```

所有导入的文件和包都被打包到可执行文件中，同时还有一份 Bun 运行时的副本。所有内置的 Bun 和 Node.js API 都受支持。

***

## 交叉编译到其他平台

使用 `--target` 标志将你的独立可执行文件编译为与你运行 `bun build` 的机器不同的操作系统、架构或 Bun 版本。

要为 Linux x64（大多数服务器）构建：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --target=bun-linux-x64 ./index.ts --outfile myapp

    # 要支持 2013 年之前的 CPU，使用 baseline 版本（nehalem）
    bun build --compile --target=bun-linux-x64-baseline ./index.ts --outfile myapp

    # 要明确仅支持 2013 年及以后的 CPU，使用 modern 版本（haswell）
    # modern 更快，但 baseline 兼容性更好。
    bun build --compile --target=bun-linux-x64-modern ./index.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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}
    // 标准 Linux x64
    await Bun.build({
      entrypoints: ["./index.ts"],
      compile: {
        target: "bun-linux-x64",
        outfile: "./myapp",
      },
    });

    // Baseline（2013 年之前的 CPU）
    await Bun.build({
      entrypoints: ["./index.ts"],
      compile: {
        target: "bun-linux-x64-baseline",
        outfile: "./myapp",
      },
    });

    // Modern（2013 年及之后的 CPU，更快）
    await Bun.build({
      entrypoints: ["./index.ts"],
      compile: {
        target: "bun-linux-x64-modern",
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

要为 Linux ARM64 构建（例如 Graviton 或 Raspberry Pi）：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    # 注意：如果未指定架构，默认架构是 x64。
    bun build --compile --target=bun-linux-arm64 ./index.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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.ts"],
      compile: {
        target: "bun-linux-arm64",
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

要为 Windows x64 构建：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --target=bun-windows-x64 ./path/to/my/app.ts --outfile myapp

    # 要支持 2013 年之前的 CPU，使用 baseline 版本（nehalem）
    bun build --compile --target=bun-windows-x64-baseline ./path/to/my/app.ts --outfile myapp

    # 要明确仅支持 2013 年及以后的 CPU，使用 modern 版本（haswell）
    bun build --compile --target=bun-windows-x64-modern ./path/to/my/app.ts --outfile myapp

    # 注意：如果未提供 .exe 扩展名，Bun 会自动为 Windows 可执行文件添加
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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}
    // 标准 Windows x64
    await Bun.build({
      entrypoints: ["./path/to/my/app.ts"],
      compile: {
        target: "bun-windows-x64",
        outfile: "./myapp", // .exe 自动添加
      },
    });

    // Baseline 或 modern 变体
    await Bun.build({
      entrypoints: ["./path/to/my/app.ts"],
      compile: {
        target: "bun-windows-x64-baseline",
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

要为 Windows arm64 构建：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --target=bun-windows-arm64 ./path/to/my/app.ts --outfile myapp

    # 注意：如果未提供 .exe 扩展名，Bun 会自动为 Windows 可执行文件添加
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./path/to/my/app.ts"],
      compile: {
        target: "bun-windows-arm64",
        outfile: "./myapp", // .exe 自动添加
      },
    });
    ```
  </Tab>
</Tabs>

要为 macOS arm64 构建：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --target=bun-darwin-arm64 ./path/to/my/app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./path/to/my/app.ts"],
      compile: {
        target: "bun-darwin-arm64",
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

要为 macOS x64 构建：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --target=bun-darwin-x64 ./path/to/my/app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./path/to/my/app.ts"],
      compile: {
        target: "bun-darwin-x64",
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

### 支持的目标平台

`--target` 值的各段可以用任何顺序出现，只要它们由 `-` 分隔即可。

| --target             | 操作系统    | 架构    | Modern | Baseline | Libc  |
| -------------------- | ------- | ----- | ------ | -------- | ----- |
| bun-linux-x64        | Linux   | x64   | ✅      | ✅        | glibc |
| bun-linux-arm64      | Linux   | arm64 | ✅      | N/A      | glibc |
| bun-windows-x64      | Windows | x64   | ✅      | ✅        | -     |
| bun-windows-arm64    | Windows | arm64 | ✅      | N/A      | -     |
| bun-darwin-x64       | macOS   | x64   | ✅      | ✅        | -     |
| bun-darwin-arm64     | macOS   | arm64 | ✅      | N/A      | -     |
| bun-linux-x64-musl   | Linux   | x64   | ✅      | ✅        | musl  |
| bun-linux-arm64-musl | Linux   | arm64 | ✅      | N/A      | musl  |

<Warning>
  在 x64 平台上，Bun 使用需要 AVX2 指令集的 SIMD 优化。没有这些指令的旧 CPU 应使用 `-baseline` 版本的 Bun。
  Bun 安装程序会检测要使用的版本，但在交叉编译时你可能不知道目标 CPU。这主要在 Windows x64 和 Linux x64 上很重要，在 Darwin x64 上很少见。如果你或你的用户看到 `"Illegal instruction"` 错误，你可能需要使用 baseline 版本。
</Warning>

***

## 构建时常量

使用 `--define` 标志将构建时常量注入到你的可执行文件中，例如版本号、构建时间戳或配置值：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./src/cli.ts"],
      compile: {
        outfile: "./mycli",
      },
      define: {
        BUILD_VERSION: JSON.stringify("1.2.3"),
        BUILD_TIME: JSON.stringify("2024-01-15T10:30:00Z"),
      },
    });
    ```
  </Tab>
</Tabs>

Bun 在构建时将这些常量内联到二进制文件中，因此运行时零成本，并支持死代码消除。

<Note>更多示例和模式，请参见[构建时常量指南](/guides/runtime/build-time-constants)。</Note>

***

## 部署到生产环境

编译后的可执行文件减少了内存使用并改善了 Bun 的启动时间。

通常，Bun 在 `import` 和 `require` 时读取并转译 JavaScript 和 TypeScript 文件。这是 Bun 许多功能"开箱即用"的原因之一，但并非免费：从磁盘读取文件、解析路径、解析、转译和打印源代码都会消耗时间和内存。

编译后的可执行文件将这些成本从运行时转移到了构建时。

部署到生产环境时，我们建议：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./path/to/my/app.ts"],
      compile: {
        outfile: "./myapp",
      },
      minify: true,
      sourcemap: "linked",
    });
    ```
  </Tab>
</Tabs>

### 字节码编译

为了改善启动时间，启用字节码编译：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --minify --sourcemap --bytecode ./path/to/my/app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./path/to/my/app.ts"],
      compile: {
        outfile: "./myapp",
      },
      minify: true,
      sourcemap: "linked",
      bytecode: true,
    });
    ```
  </Tab>
</Tabs>

使用字节码编译，`tsc` 启动快 2 倍：

<Frame>
  ![字节码性能对比](https://github.com/user-attachments/assets/dc8913db-01d2-48f8-a8ef-ac4e984f9763)
</Frame>

字节码编译将大型输入文件的解析开销从运行时转移到打包时。你的应用启动更快，代价是让 `bun build` 命令稍微慢一点。它不会混淆源代码。

<Note>与 `--compile` 一起使用时，字节码编译同时支持 `cjs` 和 `esm` 格式。</Note>

### 这些标志做了什么？

`--minify` 参数减少转译后输出代码的大小。对于大型应用，这可以节省数兆字节的空间。对于较小的应用，它可能仍然能略微改善启动时间。

`--sourcemap` 参数嵌入一个用 zstd 压缩的 sourcemap，这样错误和堆栈跟踪指向原始位置而不是转译后的位置。Bun 在发生错误时自动解压缩并解析 sourcemap。

`--bytecode` 参数启用字节码编译。每次你在 Bun 中运行 JavaScript 代码时，JavaScriptCore（引擎）都会将你的源代码编译为字节码。`--bytecode` 将该解析工作从运行时转移到打包时，从而缩短启动时间。

***

## 嵌入运行时参数

**`--compile-exec-argv="args"`** - 嵌入运行时参数，在运行时可通过 `process.execArgv` 获取：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./app.ts"],
      compile: {
        execArgv: ["--smol", "--user-agent=MyBot"],
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

```ts app.ts 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.execArgv); // ["--smol", "--user-agent=MyBot"]
```

### 通过 `BUN_OPTIONS` 传递运行时参数

独立可执行文件会读取 `BUN_OPTIONS` 环境变量，因此你可以传递运行时标志而无需重新编译：

```bash terminal icon="terminal" theme={null}
# 在编译后的可执行文件上启用 CPU 性能分析
BUN_OPTIONS="--cpu-prof" ./myapp

# 启用堆性能分析并输出 markdown
BUN_OPTIONS="--heap-prof-md" ./myapp

# 组合多个标志
BUN_OPTIONS="--smol --cpu-prof-md" ./myapp
```

***

## 自动配置加载

独立可执行文件可以自动从运行目录加载配置文件。默认情况下：

* **`tsconfig.json`** 和 **`package.json`** 加载**已禁用**——这些通常只在开发时需要，打包器在编译时已经使用了它们
* **`.env`** 和 **`bunfig.toml`** 加载**已启用**——这些通常包含可能因部署而异的运行时配置

<Note>
  在未来的 Bun 版本中，`.env` 和 `bunfig.toml` 可能也会默认禁用，以实现更确定的行为。
</Note>

### 在运行时启用配置加载

如果你的可执行文件需要在运行时读取 `tsconfig.json` 或 `package.json`，使用这些标志选择加入：

```bash icon="terminal" terminal theme={null}
# 启用运行时加载 tsconfig.json
bun build --compile --compile-autoload-tsconfig ./app.ts --outfile myapp

# 启用运行时加载 package.json
bun build --compile --compile-autoload-package-json ./app.ts --outfile myapp

# 同时启用两者
bun build --compile --compile-autoload-tsconfig --compile-autoload-package-json ./app.ts --outfile myapp
```

### 在运行时禁用配置加载

要禁用 `.env` 或 `bunfig.toml` 加载以实现确定性执行：

<Tabs>
  <Tab title="CLI">
    ```bash icon="terminal" terminal theme={null}
    # 禁用 .env 加载
    bun build --compile --no-compile-autoload-dotenv ./app.ts --outfile myapp

    # 禁用 bunfig.toml 加载
    bun build --compile --no-compile-autoload-bunfig ./app.ts --outfile myapp

    # 禁用所有配置加载
    bun build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig ./app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./app.ts"],
      compile: {
        // tsconfig.json 和 package.json 默认禁用
        autoloadTsconfig: true, // 启用 tsconfig.json 加载
        autoloadPackageJson: true, // 启用 package.json 加载

        // .env 和 bunfig.toml 默认启用
        autoloadDotenv: false, // 禁用 .env 加载
        autoloadBunfig: false, // 禁用 bunfig.toml 加载
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

***

## 作为 Bun CLI 运行

<Note>Bun v1.2.16 新增</Note>

设置 `BUN_BE_BUN=1` 环境变量，使独立可执行文件像 `bun` CLI 本身一样运行。可执行文件会忽略其打包的入口点，而是暴露完整的 `bun` CLI。

例如，考虑从这个脚本编译的可执行文件：

```bash icon="terminal" terminal theme={null}
echo "console.log(\"你不应该看到这个\");" > such-bun.js
bun build --compile ./such-bun.js
```

```txt theme={null}
[3ms] bundle 1 modules
[89ms] compile such-bun
```

通常，运行 `./such-bun` 时会带参数执行脚本。

```bash icon="terminal" terminal theme={null}
# 可执行文件默认运行自己的入口点
./such-bun install
```

```txt theme={null}
你不应该看到这个
```

然而，使用 `BUN_BE_BUN=1` 环境变量时，它就像 `bun` 二进制文件一样运行：

```bash icon="terminal" terminal theme={null}
# 使用环境变量时，可执行文件就像 `bun` CLI
BUN_BE_BUN=1 ./such-bun install
```

```txt theme={null}
bun install v1.2.16-canary.1 (1d1db811)
Checked 63 installs across 64 packages (no changes) [5.00ms]
```

基于 Bun 构建的 CLI 工具可以使用此功能来安装包、打包依赖关系或运行其他文件，而无需下载单独的二进制文件或安装 Bun。

***

## 全栈可执行文件

<Note>Bun v1.2.17 新增</Note>

`--compile` 标志可以创建一个包含服务器和客户端代码的独立可执行文件，适用于全栈应用程序。当你在服务器代码中导入 HTML 文件时，Bun 会打包前端资源（JavaScript、CSS 等）并将其嵌入到可执行文件中。

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

  const server = serve({
    routes: {
      "/": index,
      "/api/hello": { GET: () => Response.json({ message: "来自 API 的问候" }) },
    },
  });

  console.log(`服务器运行在 http://localhost:${server.port}`);
  ```

  ```html index.html icon="file-code" theme={null}
  <!DOCTYPE html>
  <html>
    <head>
      <title>我的应用</title>
      <link rel="stylesheet" href="./styles.css" />
    </head>
    <body>
      <h1>Hello World</h1>
      <script src="./app.ts"></script>
    </body>
  </html>
  ```

  ```ts app.ts icon="file-code" theme={null}
  console.log("来自客户端的问候！");
  ```

  ```css styles.css icon="file-code" theme={null}
  body {
    background-color: #f0f0f0;
  }
  ```
</CodeGroup>

要将其构建为单个可执行文件：

<Tabs>
  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build --compile ./server.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./server.ts"],
      compile: {
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

这会创建一个自包含的二进制文件，包含：

* 你的服务器代码
* Bun 运行时
* 所有前端资源（HTML、CSS、JavaScript）
* 服务器使用的任何 npm 包

结果是一个可以在任何地方部署的单一文件，无需安装 Node.js、Bun 或任何依赖：

```bash terminal icon="terminal" theme={null}
./myapp
```

Bun 以前端资源所需的正确 MIME 类型和缓存头提供它们。HTML 导入被替换为一个清单对象，`Bun.serve` 使用它来提供预打包的资源。

有关构建全栈应用的更多信息，请参阅[全栈指南](/bundler/fullstack)。

***

## Worker

要在独立可执行文件中使用 worker，将 worker 的入口点添加到构建中：

<Tabs>
  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build --compile ./index.ts ./my-worker.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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.ts", "./my-worker.ts"],
      compile: {
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

然后，在你的代码中引用 worker：

```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}
console.log("来自 Bun 的问候！");

// 以下任何一种方式都可以：
new Worker("./my-worker.ts");
new Worker(new URL("./my-worker.ts", import.meta.url));
new Worker(new URL("./my-worker.ts", import.meta.url).href);
```

当你向独立可执行文件添加多个入口点时，每个入口点都会被单独打包到可执行文件中。

我们将来可能会自动检测 `new Worker(path)` 中静态已知的路径并自动打包它们，但目前你需要将 worker 文件列为入口点，如上例所示。

如果你使用相对路径引用未包含在独立可执行文件中的文件，Bun 会相对于进程当前工作目录从磁盘加载该路径，如果文件不存在则会报错。

***

## SQLite

你可以将 `bun:sqlite` 导入与 `bun build --compile` 一起使用。

默认情况下，数据库相对于进程的当前工作目录进行解析。

```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}
import db from "./my.db" with { type: "sqlite" };

console.log(db.query("select * from users LIMIT 1").get());
```

这意味着如果可执行文件在 `/usr/bin/hello` 而用户终端在 `/home/me/Desktop`，Bun 会在 `/home/me/Desktop/my.db` 中查找。

```bash terminal icon="terminal" theme={null}
cd /home/me/Desktop
./hello
```

***

## 嵌入资源与文件

独立可执行文件可以将文件直接嵌入到二进制文件中，因此单个可执行文件可以携带你的应用所需的图片、JSON 配置、模板或任何其他资源。

### 工作原理

使用 `with { type: "file" }` [导入属性](https://github.com/tc39/proposal-import-attributes)来嵌入文件：

```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}
import icon from "./icon.png" with { type: "file" };

console.log(icon);
// 开发期间："./icon.png"
// 编译后："$bunfs/root/icon-a1b2c3d4.png"（内部路径）
```

导入返回一个指向嵌入文件的**路径字符串**。在构建时，Bun：

1. 读取文件内容
2. 将数据嵌入到可执行文件中
3. 将导入替换为内部路径（以 `/$bunfs/` 为前缀）

然后你可以使用 `Bun.file()` 或 Node.js `fs` API 读取这个嵌入的文件。

### 使用 Bun.file() 读取嵌入文件

`Bun.file()` 是读取嵌入文件的推荐方式：

```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}
import icon from "./icon.png" with { type: "file" };
import { file } from "bun";

// 以不同类型获取文件内容
const bytes = await file(icon).arrayBuffer(); // ArrayBuffer
const text = await file(icon).text(); // string（用于文本文件）
const blob = file(icon); // Blob

// 在响应中流式传输文件
export default {
  fetch(req) {
    return new Response(file(icon), {
      headers: { "Content-Type": "image/png" },
    });
  },
};
```

### 使用 Node.js fs 读取嵌入文件

嵌入文件与 Node.js 文件系统 API 兼容：

```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}
import icon from "./icon.png" with { type: "file" };
import config from "./config.json" with { type: "file" };
import { readFileSync, promises as fs } from "node:fs";

// 同步读取
const iconBuffer = readFileSync(icon);

// 异步读取
const configData = await fs.readFile(config, "utf-8");
const parsed = JSON.parse(configData);

// 检查文件属性
const stats = await fs.stat(icon);
console.log(`图标大小：${stats.size} 字节`);
```

### 实用示例

#### 嵌入 JSON 配置文件

```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}
import configPath from "./default-config.json" with { type: "file" };
import { file } from "bun";

// 加载嵌入的默认配置
const defaultConfig = await file(configPath).json();

// 如果存在用户配置则合并
const userConfig = await file("./user-config.json")
  .json()
  .catch(() => ({}));
const config = { ...defaultConfig, ...userConfig };
```

#### 在 HTTP 服务器中提供静态资源

在 `Bun.serve()` 中使用 `static` 路由实现高效的静态文件服务：

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import favicon from "./favicon.ico" with { type: "file" };
import logo from "./logo.png" with { type: "file" };
import styles from "./styles.css" with { type: "file" };
import { file, serve } from "bun";

serve({
  static: {
    "/favicon.ico": file(favicon),
    "/logo.png": file(logo),
    "/styles.css": file(styles),
  },
  fetch(req) {
    return new Response("未找到", { status: 404 });
  },
});
```

Bun 自动处理静态路由的 Content-Type 头和缓存。

#### 嵌入模板

```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}
import templatePath from "./email-template.html" with { type: "file" };
import { file } from "bun";

async function sendWelcomeEmail(user: { name: string; email: string }) {
  const template = await file(templatePath).text();
  const html = template.replace("{{name}}", user.name).replace("{{email}}", user.email);

  // 使用渲染后的模板发送邮件...
}
```

#### 嵌入二进制文件

```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}
import wasmPath from "./processor.wasm" with { type: "file" };
import fontPath from "./font.ttf" with { type: "file" };
import { file } from "bun";

// 加载 WebAssembly 模块
const wasmBytes = await file(wasmPath).arrayBuffer();
const wasmModule = await WebAssembly.instantiate(wasmBytes);

// 读取二进制字体数据
const fontData = await file(fontPath).bytes();
```

### 嵌入 SQLite 数据库

要将 SQLite 数据库嵌入到编译后的可执行文件中，在导入属性中设置 `type: "sqlite"` 并将 `embed` 属性设置为 `"true"`。

数据库文件必须已经在磁盘上存在。然后，在你的代码中导入它：

```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}
import myEmbeddedDb from "./my.db" with { type: "sqlite", embed: "true" };

console.log(myEmbeddedDb.query("select * from users LIMIT 1").get());
```

最后，编译为独立可执行文件：

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

<Note>
  运行 `bun build --compile` 时，数据库文件必须存在于磁盘上。`embed: "true"` 属性告诉打包器将数据库内容包含在编译后的可执行文件中。当正常使用 `bun run` 运行时，数据库文件就像常规的 SQLite 导入一样从磁盘加载。
</Note>

在编译后的可执行文件中，嵌入的数据库是可读写的，但所有更改在可执行文件退出时都会丢失（因为它存储在内存中）。

### 嵌入 N-API 插件

你可以将 `.node` 文件嵌入到可执行文件中。

```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}
const addon = require("./addon.node");

console.log(addon.hello());
```

如果你使用 `@mapbox/node-pre-gyp` 或类似工具，`.node` 文件必须被直接 require，否则无法正确打包。

### 嵌入目录

要使用 `bun build --compile` 嵌入目录，在构建中包含文件模式：

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

  <Tab title="JavaScript">
    ```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}
    import { Glob } from "bun";

    // 展开 glob 模式到文件列表
    const glob = new Glob("./public/**/*.png");
    const pngFiles = Array.from(glob.scanSync("."));

    await Bun.build({
      entrypoints: ["./index.ts", ...pngFiles],
      compile: {
        outfile: "./myapp",
      },
    });
    ```
  </Tab>
</Tabs>

然后，你可以从代码中引用这些文件：

```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}
import icon from "./public/assets/icon.png" with { type: "file" };
import { file } from "bun";

export default {
  fetch(req) {
    // 嵌入的文件可以从 Response 对象流式传输
    return new Response(file(icon));
  },
};
```

这是一种变通方案，我们期待用更直接的 API 替代它。

### 在运行时检测独立模式

使用 `Bun.isStandaloneExecutable` 检查当前进程是否从编译后的二进制文件运行：

```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}
if (Bun.isStandaloneExecutable) {
  // 从 `bun build --compile` 输出运行
} else {
  // 通过 `bun <file>` 或作为库运行
}
```

与 `Bun.embeddedFiles.length > 0` 不同，此检查不会为每个嵌入文件分配 `Blob` 对象，因此在嵌入大量资源的二进制文件中，在启动时调用是安全的。

### 列出嵌入文件

`Bun.embeddedFiles` 将所有嵌入文件作为 `Blob` 对象暴露：

```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}
import "./icon.png" with { type: "file" };
import "./data.json" with { type: "file" };
import "./template.html" with { type: "file" };
import { embeddedFiles } from "bun";

// 列出所有嵌入文件
for (const blob of embeddedFiles) {
  console.log(`${blob.name} - ${blob.size} 字节`);
}
// 输出：
//   icon-a1b2c3d4.png - 4096 bytes
//   data-e5f6g7h8.json - 256 bytes
//   template-i9j0k1l2.html - 1024 bytes
```

`Bun.embeddedFiles` 中的每一项都是一个带有 `name` 属性的 `Blob`：

```ts theme={null}
embeddedFiles: ReadonlyArray<Blob>;
```

使用它通过 `static` 路由提供每个嵌入资源：

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import "./public/favicon.ico" with { type: "file" };
import "./public/logo.png" with { type: "file" };
import "./public/styles.css" with { type: "file" };
import { embeddedFiles, serve } from "bun";

// 从所有嵌入文件构建静态路由
const staticRoutes: Record<string, Blob> = {};
for (const blob of embeddedFiles) {
  // 从文件名中移除哈希："icon-a1b2c3d4.png" -> "icon.png"
  const name = blob.name.replace(/-[a-f0-9]+\./, ".");
  staticRoutes[`/${name}`] = blob;
}

serve({
  static: staticRoutes,
  fetch(req) {
    return new Response("未找到", { status: 404 });
  },
});
```

<Note>
  `Bun.embeddedFiles` 排除打包的源代码（`.ts`、`.js` 等），以帮助保护你的应用源码。
</Note>

#### 内容哈希

默认情况下，嵌入文件的名称会附加一个内容哈希，这有助于在通过 URL 或 CDN 提供时进行缓存失效。要保留原始名称，请配置资源命名：

<Tabs>
  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build --compile --asset-naming="[name].[ext]" ./index.ts
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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.ts"],
      compile: {
        outfile: "./myapp",
      },
      naming: {
        asset: "[name].[ext]",
      },
    });
    ```
  </Tab>
</Tabs>

***

## 压缩

要缩减可执行文件的大小，启用压缩：

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

  <Tab title="JavaScript">
    ```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.ts"],
      compile: {
        outfile: "./myapp",
      },
      minify: true, // 启用所有压缩选项
    });

    // 或精细控制：
    await Bun.build({
      entrypoints: ["./index.ts"],
      compile: {
        outfile: "./myapp",
      },
      minify: {
        whitespace: true,
        syntax: true,
        identifiers: true,
      },
    });
    ```
  </Tab>
</Tabs>

这使用 Bun 的压缩器来减小代码大小。不过整体来说，Bun 的二进制文件仍然太大，我们需要让它变得更小。

***

## Windows 专用标志

在 Windows 上编译独立可执行文件时，平台特定的选项可以自定义生成的 `.exe` 文件的元数据：

<Tabs>
  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    # 自定义图标
    bun build --compile --windows-icon=path/to/icon.ico ./app.ts --outfile myapp

    # 隐藏控制台窗口（用于 GUI 应用）
    bun build --compile --windows-hide-console ./app.ts --outfile myapp
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./app.ts"],
      compile: {
        outfile: "./myapp",
        windows: {
          icon: "./path/to/icon.ico",
          hideConsole: true,
          // 其他 Windows 元数据：
          title: "我的应用程序",
          publisher: "我的公司",
          version: "1.0.0",
          description: "一个独立的 Windows 应用程序",
          copyright: "Copyright 2024",
        },
      },
    });
    ```
  </Tab>
</Tabs>

可用的 Windows 选项：

* `icon` - 可执行文件图标的 `.ico` 文件路径
* `hideConsole` - 禁用后台终端（用于 GUI 应用）
* `title` - 文件属性中的应用程序标题
* `publisher` - 文件属性中的发布者名称
* `version` - 文件属性中的版本字符串
* `description` - 文件属性中的描述
* `copyright` - 文件属性中的版权声明

<Warning>这些标志在交叉编译时不能使用，因为它们依赖于 Windows API。</Warning>

***

## macOS 上的代码签名

要在 macOS 上对独立可执行文件进行代码签名（修复 Gatekeeper 警告），使用 `codesign` 命令。

```bash terminal icon="terminal" theme={null}
codesign --deep --force -vvvv --sign "XXXXXXXXXX" ./myapp
```

我们建议包含一个带有 JIT 权限的 `entitlements.plist` 文件。

```xml icon="xml" title="info.plist" theme={null}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.cs.allow-jit</key>
    <true/>
    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
    <true/>
    <key>com.apple.security.cs.disable-executable-page-protection</key>
    <true/>
    <key>com.apple.security.cs.allow-dyld-environment-variables</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
</dict>
</plist>
```

要使用 JIT 支持进行代码签名，将 `--entitlements` 标志传递给 `codesign`。

```bash terminal icon="terminal" theme={null}
codesign --deep --force -vvvv --sign "XXXXXXXXXX" --entitlements entitlements.plist ./myapp
```

代码签名后，验证可执行文件：

```bash terminal icon="terminal" theme={null}
codesign -vvv --verify ./myapp
./myapp: valid on disk
./myapp: satisfies its Designated Requirement
```

<Warning>代码签名支持需要 Bun v1.2.4 或更新版本。</Warning>

***

## 代码分割

独立可执行文件支持代码分割。使用 `--compile` 和 `--splitting` 创建一个可执行文件，在运行时加载代码分割的块。

<Tabs>
  <Tab title="CLI">
    ```bash terminal icon="terminal" theme={null}
    bun build --compile --splitting ./src/entry.ts --outfile ./build/entry
    ```
  </Tab>

  <Tab title="JavaScript">
    ```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: ["./src/entry.ts"],
      compile: true,
      splitting: true,
      outdir: "./build",
    });
    ```
  </Tab>
</Tabs>

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

  // 这个动态导入被代码分割到一个单独的块中
  const { fn } = await import("./dynamic.ts");
  fn();
  ```

  ```sh terminal icon="terminal" theme={null}
  ls -la build/

  -rwxr-xr-x  1 user  staff    43M  entry
  -rw-r--r--  1 user  staff   4.3K  entry_a1b2c3d4.js  # 代码分割的块
  ```
</CodeGroup>

代码分割的块会紧挨着可执行文件生成。注意，代码分割的块不会被嵌入到可执行文件中——它们作为独立的文件保留在文件系统上。

***

## 异步插件

你可以在 `Bun.build({ plugins })` 中使用插件和 `--compile`。这使你可以在构建时应用自定义转换。

```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}
import type { BunPlugin } from "bun";

const envPlugin: BunPlugin = {
  name: "env-loader",
  setup(build) {
    build.onLoad({ filter: /\.env\.json$/ }, async args => {
      // 将 .env.json 文件转换为验证后的配置对象
      const env = await Bun.file(args.path).json();

      return {
        contents: `export default ${JSON.stringify(env)};`,
        loader: "js",
      };
    });
  },
};

await Bun.build({
  entrypoints: ["./cli.ts"],
  compile: {
    outfile: "./mycli",
  },
  plugins: [envPlugin],
});
```

用例示例——在构建时嵌入环境配置：

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

console.log(`在 ${config.environment} 模式下运行`);
console.log(`API 端点：${config.apiUrl}`);
```

插件可以执行任何转换：编译 YAML/TOML 配置、内联 SQL 查询、生成类型安全的 API 客户端或预处理模板。请参阅[插件文档](/bundler/plugins)。

***

## 不支持的 CLI 参数

`--compile` 标志不支持以下参数：

* `--outdir` —— 改用 `outfile`。
* `--public-path`
* `--target=node`
* `--target=browser`（不带 HTML 入口点——请参阅[独立 HTML](/bundler/standalone-html) 了解带 `.html` 文件的 `--compile --target=browser`）
* `--no-bundle`——Bun 总是将所有内容打包到可执行文件中。

***

## API 参考

`Bun.build()` 中的 `compile` 选项接受三种形式：

```ts title="types" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
interface BuildConfig {
  entrypoints: string[];
  compile: boolean | Bun.Build.CompileTarget | CompileBuildOptions;
  // ...其他 BuildConfig 选项（minify、sourcemap、define、plugins 等）
}

interface CompileBuildOptions {
  target?: Bun.Build.CompileTarget; // 交叉编译目标
  outfile?: string; // 输出可执行文件路径
  execArgv?: string[]; // 运行时参数（process.execArgv）
  autoloadTsconfig?: boolean; // 加载 tsconfig.json（默认：false）
  autoloadPackageJson?: boolean; // 加载 package.json（默认：false）
  autoloadDotenv?: boolean; // 加载 .env 文件（默认：true）
  autoloadBunfig?: boolean; // 加载 bunfig.toml（默认：true）
  windows?: {
    icon?: string; // .ico 文件路径
    hideConsole?: boolean; // 隐藏控制台窗口
    title?: string; // 应用程序标题
    publisher?: string; // 发布者名称
    version?: string; // 版本字符串
    description?: string; // 描述
    copyright?: string; // 版权声明
  };
}
```

使用形式：

```ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// 简单布尔值——为当前平台编译（使用入口点名称作为输出）
compile: true

// 目标字符串——交叉编译（使用入口点名称作为输出）
compile: "bun-linux-x64"

// 完整选项对象——指定输出文件和其他选项
compile: {
  target: "bun-linux-x64",
  outfile: "./myapp",
}
```

### 支持的目标

```ts title="Bun.Build.CompileTarget" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
type CompileTarget =
  | "bun-darwin-x64"
  | "bun-darwin-x64-baseline"
  | "bun-darwin-arm64"
  | "bun-linux-x64"
  | "bun-linux-x64-baseline"
  | "bun-linux-x64-modern"
  | "bun-linux-arm64"
  | "bun-linux-x64-musl"
  | "bun-linux-arm64-musl"
  | "bun-windows-x64"
  | "bun-windows-x64-baseline"
  | "bun-windows-x64-modern"
  | "bun-windows-arm64";
```

### 完整示例

```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}
import type { BunPlugin } from "bun";

const myPlugin: BunPlugin = {
  name: "my-plugin",
  setup(build) {
    // 插件实现
  },
};

const result = await Bun.build({
  entrypoints: ["./src/cli.ts"],
  compile: {
    target: "bun-linux-x64",
    outfile: "./dist/mycli",
    execArgv: ["--smol"],
    autoloadDotenv: false,
    autoloadBunfig: false,
  },
  minify: true,
  sourcemap: "linked",
  bytecode: true,
  define: {
    "process.env.NODE_ENV": JSON.stringify("production"),
    VERSION: JSON.stringify("1.0.0"),
  },
  plugins: [myPlugin],
});

if (result.success) {
  console.log("构建成功：", result.outputs[0].path);
}
```
