Lerna+GitHub Actions发布npm时依赖未更新的问题
问题描述
我的Monorepo采用Lerna.js管理,本地操作完全正常,但用于自动化npm发布的GitHub Actions工作流存在异常:当更新packages/types-lib并同步packages/server的新类型后推送到GitHub,Action仅升级packages/types-lib版本,却未更新packages/server依赖中packages/types-lib的版本。
我的GitHub Actions工作流代码如下:
name: Publish To NPM on: push: branches: - main jobs: publish: runs-on: ubuntu-latest steps: - name: "Checkout" uses: actions/checkout@v2 with: fetch-depth: 0 - name: "Use NodeJS 16.14.2" uses: actions/setup-node@v2 with: node-version: '16.14.2' - name: "Setup npm" run: | npm set @pastelabs:registry=https://registry.npmjs.org/ npm set "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" - name: Install dependencies run: | yarn install --frozen-lockfile yarn lerna bootstrap - name: Run builds # Run build of all packages run: yarn lerna run build - name: Run tests # Run tests of all packages run: yarn lerna run test - name: "Version and publish to NPM" # Interesting step env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} run: | git config user.name "${{ github.actor }}" git config user.email "${{ github.actor}}@users.noreply.github.com" if [ ${{ github.base_ref }} = develop ]; then npx --yarn lerna version patch --exact --no-private --conventional-commits --conventional-prerelease --preid beta --yes else npx --yarn lerna version patch --exact --no-private --conventional-commits --conventional-graduate --yes fi npx --yarn lerna publish from-git --yes --exact
可能原因
- Lerna默认基于提交信息和包的直接变更检测版本更新,若提交未直接关联
packages/server,则无法自动识别该包依赖的types-lib已更新,因此不会同步更新其依赖版本及自身版本。 - 强制指定
patch版本升级(lerna version patch)会跳过Lerna的自动依赖变更检测逻辑,导致依赖更新的包无法触发版本调整。 - CI环境使用的Lerna版本与本地不一致,引发依赖关联检测行为差异。
解决方案
1. 调整Lerna版本命令参数,启用自动依赖变更检测
去掉命令中强制指定的patch,让Lerna自动根据包变更及依赖关系判断版本升级幅度;若需要确保依赖types-lib的包必被更新,可添加--force-publish参数锁定目标包。同时改用项目依赖的Lerna版本,避免版本不一致问题。
修改后的版本命令片段:
git config user.name "${{ github.actor }}" git config user.email "${{ github.actor}}@users.noreply.github.com" if [ "${{ github.base_ref }}" = "develop" ]; then yarn lerna version --exact --no-private --conventional-commits --conventional-prerelease --preid beta --yes else yarn lerna version --exact --no-private --conventional-commits --conventional-graduate --force-publish='packages/server' --yes fi yarn lerna publish from-git --yes --exact
2. 检查并配置lerna.json,确保依赖更新逻辑启用
在项目根目录的lerna.json中添加或确认以下配置,确保Lerna自动更新依赖版本:
{ "command": { "version": { "allowBranch": ["main", "develop"], "conventionalCommits": true, "updateDependencies": true, "message": "chore(release): publish %s" } } }
3. 固定Lerna版本,保持本地与CI环境一致
在项目的package.json中明确指定与本地相同的Lerna版本,避免CI拉取最新版本导致行为差异:
{ "devDependencies": { "lerna": "^6.6.2" // 替换为你本地使用的版本 } }
4. 优化依赖安装步骤,确保包链接正确
调整Workflow中的安装命令,确保Lerna bootstrap正确建立本地包链接:
yarn install --frozen-lockfile yarn lerna bootstrap --no-ci
内容的提问来源于stack exchange,提问作者Cod3n0d3
相关产品推荐
相关产品推荐

