workspace: alias protocol(也可以在 pnpm 中使用) 似乎是要采取的方向。
我也尝试使用工作区协议:“my-interface-name”:“workspace:@-/some-concrete-implementation”},但它仍然会在 npm 注册表中查找包!
一定要安装 yarn 3,否则你会遇到奇怪的问题。
注意"my-interface-name": "workspace:@-/some-concrete-implementation" 的语法看起来不正确。
它应该是"@xxx/some-concrete-implementation": "workspace:*",,假设链接包的名称是"name": "@xxx/some-concrete-implementation"。
考虑到这一点,您甚至不需要创建特定的@-/name。使用工作区协议,yarn 将确保它永远不会从 npm 下载。它成为内部工作区依赖项。
PS:
Yarn 3 安装
一般来说,一个简单的yarn set version 3.0.2 && yarn plugin import workspace-tools) 就可以了。
为避免 pnp 电流限制,请检查生成的配置 .yarnrc.yml 并确保将 nmLinker 设置为“node-modules”
# Yarn 2+ supports pnp or regular node_modules installs. Use node-modules one.
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
spec: "@yarnpkg/plugin-workspace-tools"
yarnPath: .yarn/releases/yarn-3.0.2.cjs
PS:您可能也想将其添加到.gitignore
.yarn/*
!.yarn/patches
!.yarn/releases
!.yarn/plugins
!.yarn/sdks
!.yarn/versions
.pnp.*
之后运行yarn install。
关于 package.json 的
和你一样,根 package.json 将定义工作区路径:
{
"name": "monorepo",
"workspaces": [
"packages/*" // Enable package discovery in packages/* directory.
],
// ...
"devDependencies": {
"husky": "7.0.2", // Only what's needed for monorepo management
}
在您的应用中packages/app/package.json
{
"name": "my-app",
"devDependencies": {
"@types/node": "16.10.1",
//...
},
"dependencies": {
// Assuming the name of packages/shared is "@your-org/some-concrete-implementation",
// we explicitly declare the dependency on it through
// workspace: alias (package-manager perspective)
"@your-org/some-concrete-implementation": "workspace:*",
}
}
你消费的包应该声明相同的名字
{
"name": "@your-org/some-concrete-implementation",
}
奖励:Typescript 别名
如果您的项目是用 ts 编写的,您甚至可以通过以下方式复制您的路径
typescript path mapping。它将允许按原样包含文件(无需事先编译)。
按照您的示例,只需以这种方式编辑./packages/xxx/tsconfig.json
{
"compilerOptions": {
// here baseUrl is set at ./src (good practice), can
// be set to '.'
"baseUrl": "./src",
"paths": {
// Declare deps here (keep them in sync with what
// you defined in the package.json)
// PS: path are relative to baseUrl
"@your-org/some-concrete-implementation/*": ["../../some-concrete-implementation/src/*"],
// if you have a barrel in ui-lib
"@your-org/some-concrete-implementation": ["../../some-concrete-implementation/src/index"],
}
},
}
PS:对于非 typescript:babel/plugin-module-resolver 可以类似的方式使用。