运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

生命周期脚本

Bun 如何安全地处理包的生命周期脚本

npm 上的软件包可以在其 package.json 中定义_生命周期脚本_。以下是其中一些最常见的脚本,还有许多其他脚本:

  • preinstall:包安装前运行
  • postinstall:包安装后运行
  • preuninstall:包卸载前运行
  • prepublishOnly:包发布前运行

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


postinstall

postinstall 脚本非常重要。它广泛用于为以 Node.js 原生插件 实现的软件包构建或安装特定于平台的二进制文件。例如,node-sass 使用 postinstall 为 Sass 构建原生二进制文件。

package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "node-sass": "^6.0.1"
  }
}

trustedDependencies

Bun 采用“默认安全”策略:它只会为允许列表中的包运行生命周期脚本。要允许某个特定包的生命周期脚本,请将其名称添加到 package.json 中的 trustedDependencies 数组。

package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "trustedDependencies": ["node-sass"] // [!code ++]
}

将包添加到 trustedDependencies 后,安装或重新安装该包。Bun 会读取此字段并运行其生命周期脚本。

默认情况下,系统允许一个精选的、包含生命周期脚本的常用 npm 包列表。请参阅完整列表。

trustedDependencies 字段的行为

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

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

如果你想完全退出默认允许列表,又不想在每次安装时都传入 --ignore-scripts,请设置 trustedDependencies: []。如果你使用显式列表定义了 trustedDependencies,请将默认列表中仍需要运行其生命周期脚本的包(例如 sharp 或 esbuild)加入其中。Bun 将不再默认信任这些包。


--ignore-scripts

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

terminal
bun install --ignore-scripts

要将其设为项目默认值,请在 bunfig.toml 中设置 install.ignoreScripts:

bunfig.toml
[install]
ignoreScripts = true

或者在 .npmrc 中:

.npmrc
ignore-scripts=true