Monorepo

Last Edited Time
Feb 9, 2022 07:33 AM
date
Jun 13, 2019
slug
monorepo
status
Published
tags
Blog
前端工程
Lerna
Yarn
Workspace
Monorepo
NPM
必读系列
summary
多包管理工作总结
type
Post
Monorepo 实现方式在该链接已经分析的比较透彻, 一共有如下几个实现方式:
  1. Lerna + npm
  1. Lerna + yarn
  1. yarn workspace
  1. Lerna + yarn workspace
  1. yarn 3.0 + pnp

lerna

If we installed the lernal locally, we need run lerna with npx
# 版本更新工具
npx lerna-update-wizard

lerna bootstrap
lerna add circular-dependency-plugin --scope dilithium
lerna ls
lerna run test

# 打统一版本 + 发版
lerna version 2.2.1
lerna publish from-package

# add package dependency
lerna add dilithium --scope react-demo

# 批量发布
lerna exec --no-bail "npm publish"
{
  "scripts": {
    "publish": "npm run compile && lerna publish from-git",
    "version": "lerna version --conventional-commits --no-changelog --no-push",
    "version:prerelease": "npm run version -- --conventional-prerelease",
    "version:stable": "npm run version -- --conventional-graduate",
    "version:alpha": "npm run version:prerelease -- --preid=alpha",
    "version:beta": "npm run version:prerelease -- --preid=beta",
    "version:rc": "npm run version:prerelease -- --preid=rc"

		// 另外项目
		"publish": "lerna publish --conventional-commits",
    "publish:prerelease": "npm run build:npm && npm run publish -- --conventional-prerelease --no-changelog --no-push",
    "publish:stable": "npm run build:npm && npm run publish -- --conventional-graduate",
    "publish:alpha": "npm run publish:prerelease -- --preid=alpha",
    "publish:beta": "npm run publish:prerelease -- --preid=beta",
    "publish:gamma": "npm run publish:prerelease -- --preid=gamma",
    "publish:rc": "npm run publish:prerelease -- --preid=rc",
  }
}
notion image

Lerna 使用踩坑

在安装项目的过程中, 如果使用 npm installhook(例如 postinstall) 直接触发 lerna run bootstrap --hoist 的话, 会导致 npm 包提升不彻底, 会造成重复引入类型,包导致构建失败, 目前有两个解决方案:
  • 手动分开运行 npm installnpm run bootstrap
  • 加一个新的命令npm run init, 主动触发 npm installnpm run bootstrap

Yarn Workspace

优点:
  • yarn workspace 的安装速度比较快
  • 安装时不会临时更改 package.json
  • 所有依赖都安装到根项目 node_modules, 非必要情况下不会在子包中生成 node_modules
  • 安装/更新/删除单个 package 下的包的话支持也比较好
缺点:
  • 因为所有的子项目都会被链接到 node_modules 里面, 所以会有加载多个库类型的问题, 解决方法在此

依赖管理

# 安装/更新依赖到 dependencies
yarn workspace @fe-types/miniprogram-renderer add @fe-types/miniprogram-app@latest

# 或安装/更新依赖到 devDependencies
yarn workspace @fe-types/miniprogram-renderer add -D @fe-types/miniprogram-app@latest

# 删除依赖
yarn workspace @fe-types/miniprogram-renderer remove @fe-types/miniprogram-app

# 另一种交互更新依赖的方式
yarn upgrade-interactive --latest

Reference