配置依赖项
配置依赖项允许你在多个项目之间共享和集中配置文件、设置和钩子。它们在所有常规依赖项(“dependencies”、“devDependencies”、“optionalDependencies”)之前安装,使其成为设置自定义钩子、补丁和目录条目的理想选择。
配置依赖项可帮助你将所有挂钩、设置、补丁、覆盖、目录、规则保存在一个地方,并在多个存储库中使用它们。
如果你的配置依赖项按照 pnpm-plugin-*、@*/pnpm-plugin-* 或 @pnpm/plugin-* 模式命名,pnpm 将自动从包根目录加载其 pnpmfile.mjs(回退到 pnpmfile.cjs)。
Config dependencies must come from an npm registry. pnpm verifies them against their registry before installing them, so installing a new or changed config dependency offline requires cached registry metadata. A config dependency pinned with version+integrity keeps that integrity as its pin. minimumReleaseAge applies to config dependencies that are not pinned with version+integrity. pnpm installs them before any updateConfig hook runs, so a minimumReleaseAgeExclude entry added by a hook does not cover them.
Removing a package from configDependencies removes its installed link and unused lockfile entries on the next pnpm install. This also applies when you remove the entire setting. Run without --frozen-lockfile to update the lockfile after changing the declarations.
How to add a config dependency#
配置依赖项定义在你的 pnpm-workspace.yaml 文件中。 Their integrity checksums are stored in pnpm-lock.yaml (in a dedicated env lockfile document).
例如,运行 pnpm add --configmy-configs 会将此条目添加到你的 pnpm-workspace.yaml:
configDependencies:
my-configs: "1.0.0"
重要:
- 配置依赖项不能拥有自己常规的
dependencies。 They can declareoptionalDependencies, but only one level deep.optionalDependenciesofoptionalDependenciesare ignored. - 配置依赖项不能定义生命周期脚本 (例如
preinstall,postinstall等)。
通过 optionalDependencies 获取平台特定的二进制文件#
配置依赖项可以通过 optionalDependencies 提供特定于平台的二进制文件,和 esbuild 和 swc 等工具使用的模式相同。每个平台二进制包都使用 os、cpu 和/或 libc 字段声明其支持的平台,pnpm 只安装与当前主机匹配的变体。匹配的二进制文件以符号链接的形式存在于全局虚拟存储中的父配置依赖项旁边,因此从配置依赖项内部调用 require('my-config-platform-arch') 会在运行时解析。
环境锁文件会记录所有平台变体,而不管主机平台如何,因此锁文件可以在不同机器之间保持可移植性。
Each entry in optionalDependencies must be declared with an exact version (e.g. "1.2.3"). Ranges ("^1.0.0", "~1.0.0") and tags ("latest") are rejected. 这样可以保证 config-dep 安装的可复现性:对于受完整性固定保护的父级,已解析的子级不会在机器之间发生偏移。
使用方法#
Installing dependencies used in hooks#
配置依赖项在加载 .pnpmfile.mjs 中的钩子之前安装,允许你从配置包导入逻辑。
示例:
import { readPackage } from './node_modules/.pnpm-config/my-hooks/index.mjs'
export const hooks = {
readPackage
}
Updating pnpm settings dynamically#
Using the updateConfig hook, you can dynamically update pnpm's settings using config dependencies.
例如,以下 pnpmfile 向 pnpm 的配置中添加了一个新的 catalog 条目:
export const hooks = {
updateConfig (config) {
config.catalogs.default ??= {}
config.catalogs.default['is-odd'] = '1.0.0'
return config
}
}
如果将其作为配置依赖项安装:
pnpm add --config @myorg/pnpm-plugin-my-catalogs
那么你可以运行:
pnpm add is-odd@catalog:
这将安装 is-odd@1.0.0 并将以下内容添加到你的 package.json 中:
{
"dependencies": {
"is-odd": "catalog:"
}
}
这使得跨项目维护和共享集中配置和依赖项版本变得容易。
Loading patch files#
您可以引用存储在配置依赖项中的 [patch files][补丁文件]。
示例:
configDependencies:
my-patches: "1.0.0"
patchedDependencies:
react: "node_modules/.pnpm-config/my-patches/react.patch"