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

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

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

这些脚本是包管理器预期在适当时间运行的任意 shell 命令。由于运行任意代码存在安全风险，Bun 默认情况下不会执行任意生命周期脚本，这与其他的 `npm` 客户端不同。

***

## `postinstall`

`postinstall` 脚本尤其重要。它被广泛用于构建或安装针对特定平台的二进制文件，适用于作为[原生 Node.js 插件](https://nodejs.org/api/addons.html)实现的包。例如，`node-sass` 使用 `postinstall` 来构建 Sass 的原生二进制文件。

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

***

## `trustedDependencies`

Bun 是"默认安全"的：它只为允许列表中的包运行生命周期脚本。要允许特定包的生命周期脚本，请将其名称添加到 `package.json` 的 `trustedDependencies` 数组中。

```json package.json icon="file-json" theme={null}
{
  "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={null}
bun install --ignore-scripts
```

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

```toml bunfig.toml icon="settings" theme={null}
[install]
ignoreScripts = true
```

或者在 `.npmrc` 中：

```ini .npmrc icon="npm" theme={null}
ignore-scripts=true
```
