You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过nx在GitHub Actions中触发受影响项目的CI/CD流水线?

在GitHub Actions中基于Nx Affected逻辑触发依赖项目的CI流水线

核心思路

利用Nx的affected命令识别变更文件影响的所有项目,再在GitHub Actions中根据识别结果,仅执行对应项目的流水线任务。

具体实现步骤

1. 创建GitHub Actions工作流文件

在仓库的.github/workflows目录下新建nx-affected-ci.yml,内容如下:

name: Nx Affected CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  detect-affected:
    runs-on: ubuntu-latest
    outputs:
      affected-projects: ${{ steps.set-affected.outputs.affected }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # 必须拉取完整历史,才能让Nx计算版本差异

      - name: 配置Node.js环境
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: 安装依赖
        run: npm install

      - name: 识别受影响项目
        id: set-affected
        run: |
          # 用nx affected:print输出受影响项目,格式为逗号分隔字符串
          AFFECTED=$(npx nx affected:print --base=origin/main --head=HEAD --plain)
          echo "affected=$AFFECTED" >> $GITHUB_OUTPUT

  run-affected-tasks:
    needs: detect-affected
    runs-on: ubuntu-latest
    strategy:
      matrix:
        project: ${{ fromJSON('["' + needs.detect-affected.outputs.affected-projects + '"]') }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: 配置Node.js环境
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: 安装依赖
        run: npm install

      - name: 编译${{ matrix.project }}
        run: npx nx build ${{ matrix.project }}

2. 关键细节说明

  • fetch-depth: 0:必须拉取完整仓库历史,Nx需要对比base和head版本的文件差异,才能准确识别受影响项目。
  • nx affected:print:--plain参数输出纯项目名称(逗号分隔),方便后续转为矩阵任务;PR场景下可将--base改为origin/${{ github.base_ref }},适配目标分支的对比。
  • 矩阵任务:将受影响项目转为矩阵,实现并行执行每个项目的任务,可根据需求替换build为test、deploy等其他流水线步骤。

3. 适配你的仓库场景

当libraries/pdfgenerator发生变更时,Nx会自动识别出依赖它的proj1和proj2,工作流仅会触发这两个项目的编译任务,proj3不会被执行。

如果需要针对不同项目执行差异化任务(比如proj1需部署,proj2仅需测试),可在矩阵任务中添加条件判断:

- name: 部署${{ matrix.project }}
  if: matrix.project == 'proj1'
  run: npx nx deploy ${{ matrix.project }}

- name: 测试${{ matrix.project }}
  if: matrix.project == 'proj2'
  run: npx nx test ${{ matrix.project }}

内容的提问来源于stack exchange,提问作者Joey Yi Zhao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 12:35:03