如何在Lerna Monorepo中基于Nx搭建CI/CD流水线?
适配Nx的Lerna Monorepo CI/CD配置优化
核心优化方向
- 修复原配置的YAML语法错误
- 引入Nx缓存加速依赖安装与任务执行
- 在job间复用构建产物,避免重复工作
- 结合Nx特性优化版本管理与发布流程
完整CI配置示例
jobs: build-and-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # 拉取完整Git历史,支持Nx的影响范围分析 # 缓存node_modules和Nx任务缓存 - name: Setup Nx cache uses: actions/cache@v3 with: path: | node_modules .nx/cache key: ${{ runner.os }}-nx-${{ hashFiles('package-lock.json', 'nx.json') }} restore-keys: | ${{ runner.os }}-nx- - name: Install dependencies run: | npm ci # 若仍需Lerna的依赖hoisting逻辑,保留此命令;否则可移除 npm run bootstrap # 利用Nx增量执行特性运行构建 - name: Run Build run: npm run build - name: Run Tests run: npm run test # 上传构建产物,供发布阶段直接使用 - name: Upload build artifacts uses: actions/upload-artifact@v3 with: name: build-output path: | packages/**/dist packages/**/build publish: needs: build-and-test runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 persist-credentials: false # 避免Git操作权限冲突 # 下载之前构建好的产物 - name: Download build artifacts uses: actions/download-artifact@v3 with: name: build-output path: packages/ # 复用依赖缓存 - name: Setup Nx cache uses: actions/cache@v3 with: path: | node_modules .nx/cache key: ${{ runner.os }}-nx-${{ hashFiles('package-lock.json', 'nx.json') }} restore-keys: | ${{ runner.os }}-nx- - name: Install dependencies run: npm ci # CI环境下无交互更新版本 - name: Update Version run: | npx lerna version --conventional-commits --yes --no-push env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} # 基于Git标签发布已构建的产物 - name: Publish to npm run: | npx lerna publish from-git --yes env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
关键细节说明
- Nx缓存:通过缓存
.nx/cache目录,Nx会自动跳过已执行过的任务,大幅缩短重复构建/测试时间;缓存node_modules避免重复安装依赖。 - 产物复用:通过
upload-artifact和download-artifact在构建与发布job间传递产物,发布阶段无需重新构建,节省CI资源。 - 版本管理:
--conventional-commits基于提交信息自动生成语义化版本,--yes实现无交互执行,适合CI环境;from-git确保发布的是已通过测试的Git标签版本。 - 语法修正:移除原配置中
fetch-depth: 0后的多余逗号,解决YAML语法错误导致的CI失败问题。 - 权限配置:
persist-credentials: false配合GH_TOKEN避免Git操作权限冲突;NPM_TOKEN需提前在GitHub Secrets中配置npm发布令牌。
可选进阶优化
- 若想逐步迁移到Nx原生版本管理,可替换
lerna version为nx version命令,Nx同样支持语义化版本与conventional commits规则。 - 针对大型仓库,可改用Nx的
affected命令替代run-many,仅构建/测试受代码变更影响的包:# 在package.json中新增脚本 "build:affected": "nx affected --target=build"
内容的提问来源于stack exchange,提问作者smartartdev11
相关产品推荐
相关产品推荐

