Bun

生命周期脚本

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

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

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

postinstall

postinstall 脚本尤为重要。它被广泛用于为作为原生 Node.js 插件实现的包构建或安装特定于平台的二进制文件。例如,node-sass 是一个流行的包,它使用 postinstall 为 Sass 构建原生二进制文件。

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

trustedDependencies

Bun 不执行任意脚本,而是采用“默认安全”的方法。您可以将某些包添加到允许列表中,Bun 将为这些包执行生命周期脚本。要告诉 Bun 允许特定包的生命周期脚本,请将包名称添加到 package.json 中的 trustedDependencies 数组。

{
  "name": "my-app",
  "version": "1.0.0",
  "trustedDependencies": ["node-sass"]
}

添加到 trustedDependencies 后,请安装/重新安装该包。Bun 将读取此字段并为 my-trusted-package 运行生命周期脚本。

截至 Bun v1.0.16,默认允许排名前 500 的具有生命周期脚本的 npm 包。您可以在此处查看完整列表。

--ignore-scripts

要禁用所有包的生命周期脚本,请使用 --ignore-scripts 标志。

bun install --ignore-scripts