工作空间(Workspace)
pnpm 内置了对单一存储库(也称为多包存储库、多项目存储库或单体存储库)的支持, 你可以创建一个 workspace 以将多个项目合并到一个仓库中。
A workspace must have a pnpm-workspace.yaml file in its
root. A workspace also may have an .npmrc in its root.
If you are looking into monorepo management, you might also want to look into Bit.
Bit 在后台使用 pnpm,但将许多当前在由 pnpm/npm/Yarn 管理的传统工作区中手动完成的事情自动化。 There's an article about bit install that talks about it: Painless Monorepo Dependency Management with Bit.
Workspace 协议 (workspace:)
If link-workspace-packages is set to true, pnpm will link packages from the workspace if the available packages
match the declared ranges. For instance, foo@1.0.0 is linked into bar if
bar has "foo": "^1.0.0" in its dependencies and foo@1.0.0 is in the workspace. However, if bar has
"foo": "2.0.0" in dependencies and foo@2.0.0 is not in the workspace,
foo@2.0.0 will be installed from the registry. 这种行为带来了一些不确定性。
Luckily, pnpm supports the workspace: protocol. 当使用此协议时,pnpm 将拒绝解析除本地 workspace 包含的 package 之外的任何内容。 So, if you set "foo": "workspace:2.0.0", this time
installation will fail because "foo@2.0.0" isn't present in the workspace.
This protocol is especially useful when the link-workspace-packages option is
set to false. In that case, pnpm will only link packages from the workspace if
the workspace: protocol is used.
通过别名引用 workspace 包
Let's say you have a package in the workspace named foo. Usually, you would
reference it as "foo": "workspace:*".
If you want to use a different alias, the following syntax will work too:
"bar": "workspace:foo@*".
在发布之前,别名被转换为常规名称。 The above
example will become: "bar": "npm:foo@1.0.0".
通过相对路径引用 workspace 包
假如 workspace 中有两个包:
+ packages
+ foo
+ bar
bar may have foo in its dependencies declared as
"foo": "workspace:../foo". 在发布之前,这些将转换为所有包管理器支持的常规版本规范。
发布 workspace 包
When a workspace package is packed into an archive (whether it's through
pnpm pack or one of the publish commands like pnpm publish), we dynamically
replace any workspace: dependency by:
- The corresponding version in the target workspace (if you use
workspace:*,workspace:~, orworkspace:^) - 相关的 semver 范围(对于任何其他范围类型)
So for example, if we have foo, bar, qar, zoo in the workspace and they all are at version 1.5.0, the following:
{
"dependencies": {
"foo": "workspace:*",
"bar": "workspace:~",
"qar": "workspace:^",
"zoo": "workspace:^1.5.0"
}
}
将会被转化为:
{
"dependencies": {
"foo": "1.5.0",
"bar": "~1.5.0",
"qar": "^1.5.0",
"zoo": "^1.5.0"
}
}
这个功能允许你发布转化之后的包到远端,并且可以正常使用本地 workspace 中的 packages,而不需要其它中间步骤。包的使用者也可以像常规的包那样正常使用,且仍然可以受益于语义化版本。
发布工作流
workspace 中的包版本管理是一个复杂的任务,pnpm 目前也并未提供内置的解决方案。 不过,有两个不错且支持 pnpm 的版本控制工具可以使用:
For how to set up a repository using Rush, read this page.
For using Changesets with pnpm, read this guide.