别名
别名允许你安装具有自定义名称的软件包。
¥Aliases let you install packages with custom names.
假设你在整个项目中都使用 lodash
。lodash
中有一个错误破坏了你的项目。你有一个修复,但 lodash
不会合并它。通常,你可以直接从 fork 安装 lodash
(作为 git 托管的依赖)或使用不同的名称发布它。如果你使用第二种解决方案,则必须使用新的依赖名称(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
}
}