Skip to main content
Version: 10.x

查找器

已添加于:v10.16.0

¥Added in: v10.16.0

Finder 函数允许你通过包的任何属性(而不仅仅是其名称)搜索依赖图。它们可以在 .pnpmfile.cjs 中声明,并与 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.cjs and used with pnpm list and pnpm why.

定义查找器函数

¥Defining finder functions

Finder 函数在项目的 .pnpmfile.cjs 文件中的 finders 导出下声明。每个函数都会接收一个上下文对象,并且必须返回以下任一值:

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

  • true → 将此依赖包含在结果中,

    ¥true → include this dependency in the results,

  • false → 跳过

    ¥false → skip it,

  • 或者 string → 包含此依赖并打印字符串作为附加信息。

    ¥or a string → include this dependency and print the string as additional info.

示例:匹配任何 peerDependencies 中 React 17 依赖的查找器:

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

.pnpmfile.cjs
module.exports = {
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:

module.exports = {
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:

  • 查找所有具有特定许可证的软件包。

    ¥Find all packages with a specific license.

  • 检测需要最低 Node.js 版本的软件包。

    ¥Detect packages requiring a minimum Node.js version.

  • 列出所有公开二进制文件的依赖。

    ¥List all dependencies that expose binaries.

  • 打印所有软件包的资金 URL。

    ¥Print funding URLs for all packages.