Skip to main content
Version: 10.x

别名

别名允许你安装具有自定义名称的软件包。

🌐 Aliases let you install packages with custom names.

假设你在整个项目中都使用 lodashlodash 中有一个错误导致你的项目出问题。你有修复方法,但 lodash 不会合并它。通常,你要么直接从你的 fork 安装 lodash(作为 git 托管的依赖),要么以不同的名字发布它。如果使用第二种解决方案,你必须将项目中所有的 require 都替换为新的依赖名(require('lodash') => require('awesome-lodash'))。使用别名时,你还有第三种选择。

🌐 Let's assume you use lodash all over your project. There is a bug in lodash that breaks your project. You have a fix but lodash won't merge it. Normally you would either install lodash from your fork directly (as a git-hosted dependency) or publish it with a different name. If you use the second solution you have to replace all the requires in your project with the new dependency name (require('lodash') => require('awesome-lodash')). With aliases, you have a third option.

发布一个名为 awesome-lodash 的新包,并使用 lodash 作为它的别名进行安装:

🌐 Publish a new package called awesome-lodash and install it using lodash as its alias:

pnpm add lodash@npm:awesome-lodash

不需要更改代码。所有对 lodash 的引用现在都会解析为 awesome-lodash

🌐 No changes in code are needed. All the requires of lodash will now resolve to awesome-lodash.

有时你可能想在项目中使用同一个包的两个不同版本。很简单:

🌐 Sometimes you'll want to use two different versions of a package in your project. Easy:

pnpm add lodash1@npm:lodash@1
pnpm add lodash2@npm:lodash@2

现在你可以通过 require('lodash1') 引入 lodash 的第一个版本,通过 require('lodash2') 引入第二个版本。

🌐 Now you can require the first version of lodash via require('lodash1') and the second via require('lodash2').

当与钩子结合使用时,这会变得更加强大。也许你想在 node_modules 中的所有包中将 lodash 替换为 awesome-lodash。你可以使用以下 .pnpmfile.cjs 很容易地实现:

🌐 This gets even more powerful when combined with hooks. Maybe you want to replace lodash with awesome-lodash in all the packages in node_modules. You can easily achieve that with the following .pnpmfile.cjs:

function readPackage(pkg) {
if (pkg.dependencies && pkg.dependencies.lodash) {
pkg.dependencies.lodash = 'npm:awesome-lodash@^1.0.0'
}
return pkg
}

module.exports = {
hooks: {
readPackage
}
}