Yarn工作区依赖安装到根目录,子项目构建找不到依赖如何解决?
问题原因
你使用的Yarn 3.x(Berry版本)默认开启两项和Angular 12不兼容的配置:
- 默认使用*Plug'n'Play(pnp)*依赖管理模式,不会生成传统的
node_modules目录,而Angular 12 CLI不支持pnp模式 - 开启了依赖提升(hoist)逻辑,会把所有子workspace的依赖统一安装到根目录
node_modules,但Angular 12默认优先从子项目自身的node_modules路径查找依赖,所以触发路径不存在的报错
另外你执行的yarn install && yarn workspace frontend install && yarn workspace backend install命令是冗余的,Yarn workspace模式下根目录执行一次install就会自动处理所有子包的依赖,重复执行子项目install不会生效,还可能带来异常。
解决方案
按照以下步骤操作即可:
- 新增Yarn配置文件:在项目根目录新建
.yarnrc.yml文件,添加如下配置:
# 启用传统node_modules依赖模式,兼容Angular 12 nodeLinker: node-modules # 限制依赖提升范围,各workspace的依赖安装到自身目录,不提升到根 nmHoistingLimits: workspaces
- 清理历史缓存文件:在根目录执行命令清理冗余文件:
rm -rf node_modules frontend/node_modules backend/node_modules .yarn/cache yarn.lock
- 重新安装依赖:直接在根目录执行一次
yarn install即可。 - 验证构建:执行
yarn workspace frontend ng build即可正常运行。
内容的提问来源于stack exchange,提问作者Aurelia Peters
相关产品推荐
相关产品推荐

