Skip to main content
Version: 11.x

查找器

新增于:v10.16.0

🌐 Added in: v10.16.0

Finder 函数允许你 通过包的任意属性搜索依赖图,而不仅仅是按名称搜索。它们可以在 .pnpmfile.mjs 中声明,并与 pnpm listpnpm why 一起使用。

🌐 Finder functions let you search your dependency graph by any property of a package, not just its name. They can be declared in .pnpmfile.mjs and used with pnpm list and pnpm why.

定义查找器函数

🌐 Defining finder functions

查找器函数在你项目的 .pnpmfile.mjs 文件中声明,位于 finders 导出下。 每个函数都会接收一个上下文对象,并且必须返回以下之一:

🌐 Finder functions are declared in your project’s .pnpmfile.mjs file under the finders export. Each function receives a context object and must return either:

  • true → 在结果中包含此依赖,
  • false → 跳过它,
  • 或者一个 string → 包含此依赖并将字符串作为附加信息打印出来。

示例:一个可以匹配 peerDependencies 中任何带有 React 17 的依赖的查找器:

🌐 Example: a finder that matches any dependency with React 17 in peerDependencies:

.pnpmfile.mjs
export const finders = {
react17: (ctx) => {
return ctx.readManifest().peerDependencies?.react === "^17.0.0"
}
}

查找器上下文 (ctx)

🌐 Finder context (ctx)

每个查找器函数都会接收一个描述正在访问的依赖节点的上下文对象。

🌐 Each finder function receives a context object that describes the dependency node being visited.

字段类型/示例描述
name"minimist"包名称。
version"1.2.8"包版本。
readManifest()返回 package.json 对象加载包清单(用于像 peerDependencieslicenseengines 等字段)。

使用查找器

🌐 Using finders

你可以使用 --find-by=<functionName> 标志调用查找器:

🌐 You can invoke a finder with the --find-by=<functionName> flag:

pnpm why --find-by=react17

输出:

🌐 Output:

@apollo/client 4.0.4
├── @graphql-typed-document-node/core 3.2.0
└── graphql-tag 2.12.6

返回额外元数据

🌐 Returning extra metadata

查找器也可以返回一个字符串。该字符串将显示在输出中与匹配的包一起。

🌐 A finder can also return a string. That string will be shown alongside the matched package in the output.

示例:打印软件包许可证:

🌐 Example: print the package license:

export const finders = {
react17: (ctx) => {
const manifest = ctx.readManifest()
if (manifest.peerDependencies?.react === "^17.0.0") {
return `license: ${manifest.license}`
}
return false
}
}

输出:

🌐 Output:

@apollo/client 4.0.4
├── @graphql-typed-document-node/core 3.2.0
│ license: MIT
└── graphql-tag 2.12.6
license: MIT

其他示例用例:

🌐 Othere example use cases:

  • 查找所有具有特定许可证的软件包。
  • 检测需要最低 Node.js 版本的软件包。
  • 列出所有公开二进制文件的依赖。
  • 打印所有软件包的资金 URL。