> ## 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 运行时

> 使用 Bun 快速运行时执行 JavaScript/TypeScript 文件、package.json 脚本和可执行包

Bun 运行时设计为启动快、运行快。

Bun 使用由 Apple 为 Safari 开发的 [JavaScriptCore 引擎](https://developer.apple.com/documentation/javascriptcore)。它通常比 Node.js 和 Chromium 浏览器使用的 V8 引擎启动和运行更快。Bun 的转译器和运行时由 Rust 编写。在 Linux 上，Bun 的启动速度比 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={null}
bun run index.js
```

Bun 无需配置即可支持 TypeScript 和 JSX。Bun 在运行前会使用其原生[转译器](/runtime/transpiler)实时转译每个文件。

```bash terminal icon="terminal" theme={null}
bun run index.js
bun run index.jsx
bun run index.ts
bun run index.tsx
```

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

```bash terminal icon="terminal" theme={null}
bun index.tsx
bun index.js
```

### `--watch`

要以监视模式运行文件，请使用 `--watch` 标志。

```bash terminal icon="terminal" theme={null}
bun --watch run index.tsx
```

<Note>
  使用 `bun run` 时，将 `--watch` 等 Bun 标志紧跟在 `bun` 之后。

  ```bash theme={null}
  bun --watch run dev # ✔️ 这样做
  bun run dev --watch # ❌ 不要这样做
  ```

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

## 运行 `package.json` 脚本

<Note>
  对比 `npm run <script>` 或 `yarn <script>`
</Note>

```sh theme={null}
bun [bun flags] run <script> [script flags]
```

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

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

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

```bash terminal icon="terminal" theme={null}
bun run clean
rm -rf dist && echo 'Done.'
```

```txt theme={null}
Cleaning...
Done.
```

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

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

你也可以使用更短的命令 `bun <script>` 来运行脚本。如果内置的 `bun` 命令同名，则内置命令优先；请使用显式的 `bun run <script>` 来运行你的包脚本。

```bash terminal icon="terminal" theme={null}
bun run dev
```

要查看可用脚本列表，请不带参数运行 `bun run`。

```bash terminal icon="terminal" theme={null}
bun run
```

```txt theme={null}
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/span-inc/82N53aP7NFbaCVSl/icons/javascript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=48bd3119866790424aa113cd09edda91" theme={null}
#!/usr/bin/env node

// 执行操作
```

默认情况下，Bun 遵循此 shebang 并使用 `node` 执行脚本。`--bun` 标志会覆盖此行为：CLI 将使用 Bun 而非 Node.js 运行。

```bash terminal icon="terminal" theme={null}
bun run --bun vite
```

### 过滤

在 monorepo 中，`--filter` 参数可以同时在多个包中运行脚本。

`bun run --filter <name_pattern> <script>` 会在名称匹配 `<name_pattern>` 的每个包中执行 `<script>`。
例如，如果你有子目录包含名为 `foo`、`bar` 和 `baz` 的包，运行

```bash terminal icon="terminal" theme={null}
bun run --filter 'ba*' <script>
```

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

参见 [`--filter`](/pm/filter#running-scripts-with-filter)。

## `bun run -` 从 stdin 管道读取代码

`bun run -` 从 stdin 读取 JavaScript、TypeScript、TSX 或 JSX，并在不先写入临时文件的情况下执行。

```bash terminal icon="terminal" theme={null}
echo "console.log('Hello')" | bun run -
```

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

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

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

```txt theme={null}
This is TypeScript!
```

`bun run -` 将所有输入视为支持 JSX 的 TypeScript。

## `bun run --console-depth`

使用 `--console-depth` 标志控制控制台输出中对象检查的深度。

```bash terminal icon="terminal" theme={null}
bun --console-depth 5 run index.tsx
```

`--console-depth` 设置 `console.log()` 输出中嵌套对象的显示深度。默认深度为 `2`。较大的值会显示更多嵌套属性，但对于复杂对象可能会产生冗长的输出。

```ts console.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// 使用 --console-depth 2（默认）：{ a: { b: { c: [Object] } } }
// 使用 --console-depth 4：{ a: { b: { c: { d: 'deep' } } } }
```

## `bun run --smol`

在内存受限的环境中，使用 `--smol` 标志以减少内存使用，但会牺牲性能。

```bash terminal icon="terminal" theme={null}
bun --smol run index.tsx
```

`--smol` 使垃圾回收器更频繁地运行，这可能会降低执行速度。Bun 会根据可用内存（考虑 cgroups 和其他内存限制）在有或没有 `--smol` 标志的情况下调整垃圾回收器的堆大小，因此该标志主要在你希望堆增长更慢时有用。

## 解析顺序

绝对路径和以 `./` 或 `.\\` 开头的路径始终作为源文件执行。除非你使用 `bun run`，否则带有允许扩展名的名称会解析为文件而非 `package.json` 脚本。

当 `package.json` 脚本和文件同名时，`bun run` 优先使用脚本。完整的解析顺序为：

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={null}
bun run <file or script>
```

### 通用执行选项

<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">
  在 Bun 运行时中使用最新的匹配版本，始终检查 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 标头的最大大小（字节）。默认 16 KiB
</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">
  解析文件和入口点的绝对路径。这只是更改进程的 cwd
</ParamField>

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

## 示例

运行 JavaScript 或 TypeScript 文件：

```bash theme={null}
bun run ./index.js
bun run ./index.tsx
```

运行 package.json 脚本：

```bash theme={null}
bun run dev
bun run lint
```
