> ## 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 如何安全地处理包的生命周期脚本

`npm` 上的包可以在其 `package.json` 文件中定义\_生命周期脚本\_。下面是一些最常见的脚本，但实际上还有[许多其他脚本](https://docs.npmjs.com/cli/v10/using-npm/scripts)。

* `preinstall`：包安装前运行
* `postinstall`：包安装后运行
* `preuninstall`：包卸载前运行
* `prepublishOnly`：包发布前运行

这些脚本是任意的 shell 命令，包管理器会在适当的时候读取并执行它们。但是执行任意脚本存在潜在的安全风险，因此——与其他 `npm` 客户端不同——Bun 默认不执行任意的生命周期脚本。

***

## `postinstall`

`postinstall` 脚本尤其重要。它被广泛用于构建或安装平台特定的二进制文件，这些包通常实现为[本地 Node.js 插件（native add-ons）](https://nodejs.org/api/addons.html)。例如，`node-sass` 是一个流行的包，使用 `postinstall` 来构建 Sass 的本地二进制文件。

```json package.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "node-sass": "^6.0.1"
  }
}
```

***

## `trustedDependencies`

Bun 采取“默认安全”的策略，而不是执行任意脚本。你可以将某些包添加到允许列表中，Bun 会为这些包执行生命周期脚本。要允许 Bun 执行特定包的生命周期脚本，只需在你的 `package.json` 中将该包名添加到 `trustedDependencies` 数组。

```json package.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "name": "my-app",
  "version": "1.0.0",
  "trustedDependencies": ["node-sass"] // [!code ++]
}
```

添加到 `trustedDependencies` 后，安装或重新安装该包。Bun 会读取此字段并运行对应包的生命周期脚本。

一份经过筛选的、带有生命周期脚本的常见 npm 包列表默认是允许的。你可以在[这里](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt)查看完整列表。

<Note>
  默认信任的依赖列表仅适用于从 npm 安装的包。对于来自其他来源的包（例如 `file:`、`link:`、`git:` 或 `github:` 依赖），即使包名匹配默认列表中的条目，也必须显式将其添加到 `trustedDependencies` 中才能运行它们的生命周期脚本。这样可以防止恶意包通过本地文件路径或 git 仓库伪装成受信任包。
</Note>

### `trustedDependencies` 字段的行为

在 `package.json` 中定义 `trustedDependencies` 会**替换**默认列表，而不是在其基础上扩展。每个项目只会应用以下三种模式中的一种：

| `package.json`                        | 允许运行生命周期脚本的包            |
| ------------------------------------- | ----------------------- |
| 省略 `trustedDependencies`              | Bun 内置列表中的包（仅限 npm 来源）。 |
| `trustedDependencies: ["pkg-a", ...]` | **仅**列出的包。默认列表会被忽略。     |
| `trustedDependencies: []`             | **没有**任何包，包括默认列表中的包。    |

当你想完全放弃默认允许列表，而又不想在每次安装时都传入 `--ignore-scripts`，可以设置 `trustedDependencies: []`。如果你定义了显式的 `trustedDependencies` 列表，请把你仍然需要其生命周期脚本的[默认列表](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt)中的包也一并包含进去（例如 `sharp` 或 `esbuild`）——它们将不再被隐式信任。

***

## `--ignore-scripts`

如果想禁用所有包的生命周期脚本，可以使用 `--ignore-scripts` 参数。

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

要将其设为项目默认值，请在 `bunfig.toml` 中设置 [`install.ignoreScripts`](/runtime/bunfig#install-ignorescripts)：

```toml bunfig.toml icon="settings" theme={"theme":{"light":"github-light","dark":"dracula"}}
[install]
ignoreScripts = true
```

或者在 `.npmrc` 中：

```ini .npmrc icon="npm" theme={"theme":{"light":"github-light","dark":"dracula"}}
ignore-scripts=true
```
