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

# Bun 运行时

> 使用 Bun 的快速运行时执行 JavaScript/TypeScript 文件、package.json 脚本及可执行程序包。

Bun 运行时旨在快速启动与高效运行。

底层，Bun 使用了由 Apple 为 Safari 开发的 [JavaScriptCore 引擎](https://developer.apple.com/documentation/javascriptcore)。在大多数情况下，启动和运行性能均优于 Node.js 和基于 Chromium 浏览器使用的 V8 引擎。其转译器与运行时均用现代高性能语言 Zig 编写。在 Linux 上，启动速度比 Node.js 快 [4 倍](https://twitter.com/jarredsumner/status/1499225725492076544)。

| 命令              | 时间       |
| --------------- | -------- |
| `bun hello.js`  | `5.2ms`  |
| `node hello.js` | `25.1ms` |

此基准基于在 Linux 上运行一个 Hello World 脚本。

## 运行文件

使用 `bun run` 执行源文件。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run index.js
```

Bun 开箱即用支持 TypeScript 和 JSX。每个文件由 Bun 快速的本地转译器即时转译后执行。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run index.js
bun run index.jsx
bun run index.ts
bun run index.tsx
```

或者，你可以省略 `run` 关键字，使用裸命令，行为完全相同。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun index.tsx
bun index.js
```

### `--watch`

使用 `--watch` 标志可以以监听模式运行文件。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun --watch run index.tsx
```

<Note>
  使用 `bun run` 时，Bun 的标志如 `--watch` 应紧跟在 `bun` 后面。

  ```bash theme={"theme":{"light":"github-light","dark":"dracula"}}
  bun --watch run dev # ✔️ 推荐这样写
  bun run dev --watch # ❌ 不推荐这样写
  ```

  命令末尾的标志会被忽略，并传递给 `"dev"` 脚本本身。
</Note>

## 运行 `package.json` 脚本

<Note>
  与 `npm run <script>` 或 `yarn <script>` 类似
</Note>

```sh theme={"theme":{"light":"github-light","dark":"dracula"}}
bun [bun 标志] run <script> [脚本标志]
```

你的 `package.json` 可以定义很多对应 shell 命令的命名 `"scripts"`。

```json package.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  // ... 其他字段
  "scripts": {
    "clean": "rm -rf dist && echo 'Done.'",
    "dev": "bun server.ts"
  }
}
```

用 `bun run <script>` 执行这些脚本。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run clean
rm -rf dist && echo 'Done.'
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
Cleaning...
Done.
```

Bun 在子 shell 中执行脚本命令。在 Linux 和 macOS 上，按顺序检查并使用第一个找到的 shell：`bash`、`sh`、`zsh`。在 Windows 上，Bun 使用 [bun shell](/runtime/shell) 来支持类 bash 语法和许多常见命令。

<Note>⚡️ Linux 上 `npm run` 的启动时间约为 170ms；Bun 仅需 `6ms`。</Note>

脚本也可用更简洁的命令 `bun <script>` 运行，然而如果名称与 Bun 内置命令冲突，内置命令优先。此时请使用更明确的 `bun run <script>` 执行包脚本。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run dev
```

要查看可用脚本列表，无需参数直接运行 `bun run`。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
quickstart scripts:

 bun run clean
   rm -rf dist && echo 'Done.'

 bun run dev
   bun server.ts

2 scripts
```

Bun 支持生命周期钩子。例如，`bun run clean` 会执行 `preclean` 和 `postclean`（如果定义）。若 `pre<script>` 失败，Bun 不会执行主脚本。

### `--bun`

通常 `package.json` 脚本会引用本地安装的 CLI，如 `vite` 或 `next`。这些 CLI 常是带有 [shebang](https://en.wikipedia.org/wiki/Shebang_\(Unix\)) 的 JavaScript 文件，表明用 `node` 执行。

```js cli.js icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/javascript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=14ec2cbdf78f597f421d87adcffda9ac" theme={"theme":{"light":"github-light","dark":"dracula"}}
#!/usr/bin/env node

// do stuff
```

默认情况下，Bun 会尊重此 shebang，用 `node` 执行该脚本。你可用 `--bun` 标志覆写此行为。对于基于 Node.js 的 CLI，将用 Bun 代替 Node.js 执行。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run --bun vite
```

### 过滤执行

在包含多个包的 monorepo 中，可以用 `--filter` 参数一次执行多个包中的脚本。

使用 `bun run --filter <name_pattern> <script>` 使 `<script>` 在所有包名匹配 `<name_pattern>` 的包内执行。

例如，若有包含名为 `foo`、`bar` 和 `baz` 的包子目录，运行

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run --filter 'ba*' <script>
```

会在 `bar` 和 `baz` 中执行 `<script>`，而不会在 `foo` 中执行。

更多详情见文档页 [filter](/pm/filter#running-scripts-with-filter)。

## `bun run -` 从 stdin 管道执行代码

`bun run -` 允许从标准输入读取 JavaScript、TypeScript、TSX 或 JSX 代码，并执行，无需先写入临时文件。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
echo "console.log('Hello')" | bun run -
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
Hello
```

你也可以用 `bun run -` 把文件重定向给 Bun。例如，把 `.js` 文件当作 `.ts` 文件运行：

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
echo "console.log!('This is TypeScript!' as any)" > secretly-typescript.js
bun run - < secretly-typescript.js
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
This is TypeScript!
```

为方便起见，使用 `bun run -` 时，所有代码均视为带 JSX 支持的 TypeScript。

## `bun run --console-depth`

用 `--console-depth` 标志控制 `console.log()` 输出中对象检查的深度。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun --console-depth 5 run index.tsx
```

此设置决定 `console.log()` 中显示对象的嵌套层数。默认深度是 `2`。更高的值显示更多嵌套属性，但复杂对象输出可能较冗长。

```ts console.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// --console-depth 2 (默认): { a: { b: [Object] } }
// --console-depth 4: { a: { b: { c: { d: 'deep' } } } }
```

## `bun run --smol`

在内存受限环境中，使用 `--smol` 标志以降低内存使用，但会降低性能。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun --smol run index.tsx
```

这会导致垃圾回收更频繁运行，可能减慢执行速度。但在内存有限环境中很有用。Bun 会基于可用内存（考虑 cgroups 和其他内存限制）自动调整垃圾回收堆大小，有无 `--smol` 标志，故此选项主要适合希望堆增长更缓慢的情况。

## 解析顺序

绝对路径及以 `./` 或 `.\\` 开头的路径总是作为源文件执行。除非使用 `bun run`，运行带允许扩展名的文件优先使用该文件，而非 package.json 脚本。

当存在同名 package.json 脚本与文件时，`bun run` 优先执行 package.json 脚本。完整解析顺序为：

1. package.json 脚本，例如 `bun run build`
2. 源文件，例如 `bun run src/main.js`
3. 项目包中的二进制文件，例如 `bun add eslint && bun run eslint`
4. （仅 `bun run`）系统命令，例如 `bun run ls`

***

# CLI 用法

```bash theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run <文件或脚本>
```

### 常规执行选项

<ParamField path="--silent" type="boolean">
  不打印脚本命令
</ParamField>

<ParamField path="--if-present" type="boolean">
  如果入口点不存在，则退出且不报错
</ParamField>

<ParamField path="--eval" type="string">
  将参数作为脚本执行。别名：<code>-e</code>
</ParamField>

<ParamField path="--print" type="string">
  将参数作为脚本执行并打印结果。别名：<code>-p</code>
</ParamField>

<ParamField path="--help" type="boolean">
  显示此菜单后退出。别名：<code>-h</code>
</ParamField>

### 工作空间管理

<ParamField path="--elide-lines" type="number" default="10">
  使用 --filter 时显示的脚本输出行数（默认：10）。设置为 0 显示所有行
</ParamField>

<ParamField path="--filter" type="string">
  在匹配该模式的所有工作空间包中运行脚本。别名：<code>-F</code>
</ParamField>

<ParamField path="--workspaces" type="boolean">
  在所有工作空间包（来自 <code>package.json</code> 中的 <code>workspaces</code> 字段）中运行脚本
</ParamField>

<ParamField path="--parallel" type="boolean">
  并发运行多个脚本或工作空间脚本，并带有前缀输出
</ParamField>

<ParamField path="--sequential" type="boolean">
  依次运行多个脚本或工作空间脚本，并带有前缀输出
</ParamField>

<ParamField path="--no-exit-on-error" type="boolean">
  使用 <code>--parallel</code> 或 <code>--sequential</code> 时，当某脚本失败，继续执行其他脚本
</ParamField>

### 运行时及进程控制

<ParamField path="--bun" type="boolean">
  强制脚本或包使用 Bun 运行时而非 Node.js（通过软链接 node）。别名：<code>-b</code>
</ParamField>

<ParamField path="--shell" type="string">
  控制 <code>package.json</code> 脚本所用的 shell，支持 <code>bun</code> 或 <code>system</code>
</ParamField>

<ParamField path="--smol" type="boolean">
  使用更少内存，但更频繁地进行垃圾回收
</ParamField>

<ParamField path="--expose-gc" type="boolean">
  在全局对象上暴露 <code>gc()</code>。对 <code>Bun.gc()</code> 无影响
</ParamField>

<ParamField path="--no-deprecation" type="boolean">
  抑制所有自定义弃用警告
</ParamField>

<ParamField path="--throw-deprecation" type="boolean">
  决定弃用警告是否导致错误
</ParamField>

<ParamField path="--title" type="string">
  设置进程标题
</ParamField>

<ParamField path="--zero-fill-buffers" type="boolean">
  强制 <code>Buffer.allocUnsafe(size)</code> 填充为零
</ParamField>

<ParamField path="--no-addons" type="boolean">
  调用 <code>process.dlopen</code> 时抛出错误，并禁用导出条件 <code>node-addons</code>
</ParamField>

<ParamField path="--unhandled-rejections" type="string">
  以下之一：<code>strict</code>、<code>throw</code>、<code>warn</code>、<code>none</code>，或{" "}
  <code>warn-with-error-code</code>
</ParamField>

<ParamField path="--console-depth" type="number" default="2">
  设置 <code>console.log</code> 对象检查的默认深度（默认：2）
</ParamField>

### 开发工作流

<ParamField path="--watch" type="boolean">
  文件变更时自动重启进程
</ParamField>

<ParamField path="--hot" type="boolean">
  在 Bun 运行时、测试运行器或打包器中启用自动重载
</ParamField>

<ParamField path="--no-clear-screen" type="boolean">
  在启用 --hot 或 --watch 时，禁止重新加载时清屏
</ParamField>

### 调试

<ParamField path="--inspect" type="string">
  激活 Bun 的调试器
</ParamField>

<ParamField path="--inspect-wait" type="string">
  激活 Bun 的调试器，执行前等待连接
</ParamField>

<ParamField path="--inspect-brk" type="string">
  激活 Bun 的调试器，在代码第一行设置断点并等待
</ParamField>

### 依赖与模块解析

<ParamField path="--preload" type="string">
  在其他模块加载之前导入模块。别名：<code>-r</code>
</ParamField>

<ParamField path="--require" type="string">
  \--preload 别名，为 Node.js 兼容性设计
</ParamField>

<ParamField path="--import" type="string">
  \--preload 别名，为 Node.js 兼容性设计
</ParamField>

<ParamField path="--no-install" type="boolean">
  禁用 Bun 运行时自动安装
</ParamField>

<ParamField path="--install" type="string" default="auto">
  配置自动安装行为。值为 <code>auto</code>（默认，node\_modules 不存在时自动安装），{" "}
  <code>fallback</code>（缺失包时安装），<code>force</code>（始终安装）
</ParamField>

<ParamField path="-i" type="boolean">
  执行时自动安装依赖。等同于 --install=fallback
</ParamField>

<ParamField path="--prefer-offline" type="boolean">
  跳过 Bun 运行时中的包陈旧检查，优先从磁盘解析
</ParamField>

<ParamField path="--prefer-latest" type="boolean">
  使用最新匹配版本包，始终检查 npm
</ParamField>

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

<ParamField path="--main-fields" type="string">
  在 <code>package.json</code> 中查找的主要字段，默认依赖于 --target
</ParamField>

<ParamField path="--preserve-symlinks" type="boolean">
  解析文件时保留符号链接
</ParamField>

<ParamField path="--preserve-symlinks-main" type="boolean">
  解析主入口点时保留符号链接
</ParamField>

<ParamField path="--extension-order" type="string" default=".tsx,.ts,.jsx,.js,.json">
  默认值：<code>.tsx,.ts,.jsx,.js,.json</code>
</ParamField>

### 转译与语言特性

<ParamField path="--tsconfig-override" type="string">
  指定自定义 <code>tsconfig.json</code>，默认 <code>\$cwd/tsconfig.json</code>
</ParamField>

<ParamField path="--define" type="string">
  解析时替换 K:V，例如 <code>--define process.env.NODE\_ENV:"development"</code>。值以 JSON 格式解析。别名：<code>-d</code>
</ParamField>

<ParamField path="--drop" type="string">
  移除函数调用，例如 <code>--drop=console</code> 会移除所有 <code>console.\*</code> 调用
</ParamField>

<ParamField path="--loader" type="string">
  通过 <code>.ext:loader</code> 解析文件，例如 <code>--loader .js:jsx</code>。有效的加载器包括 <code>js</code>、{" "}
  <code>jsx</code>、<code>ts</code>、<code>tsx</code>、<code>json</code>、<code>toml</code>、<code>text</code>、{" "}
  <code>file</code>、<code>wasm</code>、<code>napi</code>。别名：<code>-l</code>
</ParamField>

<ParamField path="--no-macros" type="boolean">
  禁止在打包器、转译器和运行时执行宏
</ParamField>

<ParamField path="--jsx-factory" type="string">
  改变使用经典 JSX 运行时编译 JSX 元素时调用的函数
</ParamField>

<ParamField path="--jsx-fragment" type="string">
  改变编译 JSX 片段时调用的函数
</ParamField>

<ParamField path="--jsx-import-source" type="string" default="react">
  声明用于导入 jsx 和 jsxs 工厂函数的模块标识符。默认：<code>react</code>
</ParamField>

<ParamField path="--jsx-runtime" type="string" default="automatic">
  <code>automatic</code>（默认）或 <code>classic</code>
</ParamField>

<ParamField path="--jsx-side-effects" type="boolean">
  将 JSX 元素视为具有副作用（禁用纯注释）
</ParamField>

<ParamField path="--ignore-dce-annotations" type="boolean">
  忽略诸如 <code>@**PURE**</code> 的树摇注释
</ParamField>

### 网络与安全

<ParamField path="--port" type="number">
  设置 <code>Bun.serve</code> 的默认端口
</ParamField>

<ParamField path="--fetch-preconnect" type="string">
  加载代码时对 URL 进行预连接
</ParamField>

<ParamField path="--max-http-header-size" type="number" default="16384">
  设置 HTTP 头最大字节数，默认 16KiB
</ParamField>

<ParamField path="--dns-result-order" type="string" default="verbatim">
  设置 DNS 查询结果的默认顺序。有效值：<code>verbatim</code>（默认）、<code>ipv4first</code>、{" "}
  <code>ipv6first</code>
</ParamField>

<ParamField path="--use-system-ca" type="boolean">
  使用系统的受信任证书颁发机构
</ParamField>

<ParamField path="--use-openssl-ca" type="boolean">
  使用 OpenSSL 的默认 CA 存储
</ParamField>

<ParamField path="--use-bundled-ca" type="boolean">
  使用捆绑的 CA 存储
</ParamField>

<ParamField path="--redis-preconnect" type="boolean">
  启动时预连接 <code>\$REDIS\_URL</code>
</ParamField>

<ParamField path="--sql-preconnect" type="boolean">
  启动时预连接 PostgreSQL
</ParamField>

<ParamField path="--user-agent" type="string">
  设置 HTTP 请求的默认 User-Agent 头
</ParamField>

### 全局配置与上下文

<ParamField path="--env-file" type="string">
  从指定文件加载环境变量
</ParamField>

<ParamField path="--cwd" type="string">
  解析文件 & 入口点的绝对路径。仅更改进程的当前工作目录
</ParamField>

<ParamField path="--config" type="string">
  指定 Bun 配置文件路径。默认 <code>\$cwd/bunfig.toml</code>。别名：<code>-c</code>
</ParamField>

## 示例

运行一个 JavaScript 或 TypeScript 文件：

```bash theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run ./index.js
bun run ./index.tsx
```

运行 package.json 脚本：

```bash theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run dev
bun run lint
```
