修改工作流以包含策略矩阵
strategy 关键字用于配置构建矩阵(build matrix)。我们将定义一个只包含一个键 node-version 的矩阵。
- 在你的
github-actions-demo 的 GitHub 仓库页面上,点击绿色的 Code 按钮。
- 确保选择了 HTTPS 标签页,并复制 URL。它应该看起来像
https://github.com/your-username/github-actions-demo.git。
- 在 LabEx 环境中打开终端。默认路径是
~/project。
- 使用
git clone 命令下载仓库。将 your-username 替换为你实际的 GitHub 用户名。
cd ~/project
git clone https://github.com/your-username/github-actions-demo.git
示例输出:
Cloning into 'github-actions-demo'...
remote: Enumerating objects: X, done.
remote: Counting objects: 100% (X/X), done.
remote: Total X (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (X/X), done.
- 进入克隆的仓库目录:
cd ~/project/github-actions-demo
-
使用 WebIDE 编辑器创建一个新的工作流文件 .github/workflows/matrix-build.yml。你可以在左侧文件浏览器中 project/github-actions-demo/.github/workflows/ 下找到该文件。
-
首先创建基本的工作流结构。添加工作流名称和触发器:
name: Matrix Build
on: [push]
- 现在添加
jobs(任务)部分,包含一个基本的构建任务结构:
jobs:
build:
runs-on: ubuntu-latest
- 添加矩阵策略。这是启用使用多个 Node.js 版本运行任务的关键部分:
strategy:
matrix:
node-version: [18, 20, 22]
这定义了一个矩阵变量 node-version,它有三个值。GitHub Actions 将为每个值创建一个独立(separate)的任务。
- 添加
steps(步骤)部分。首先,添加 checkout 步骤:
steps:
- uses: actions/checkout@v4
- 添加 Node.js 设置步骤。注意我们如何使用
${{ matrix.node-version }} 来引用当前的矩阵值:
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- 添加安装依赖的步骤:
- name: Install dependencies
run: npm install
- 添加构建步骤,该步骤会创建 artifact(产物)目录:
- name: Build project
run: |
mkdir dist
echo "This is the build artifact" > dist/build.txt
- 添加运行测试的步骤:
- name: Run tests
run: npm test
- 最后,添加上传 artifact 的步骤。注意 artifact 的名称如何包含矩阵版本,以确保每个 artifact 都是唯一的:
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: build-assets-${{ matrix.node-version }}
path: dist
完成更改后,你的完整文件现在应该如下所示:
name: Matrix Build
on: [push]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Install dependencies
run: npm install
- name: Build project
run: |
mkdir dist
echo "This is the build artifact" > dist/build.txt
- name: Run tests
run: npm test
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: build-assets-${{ matrix.node-version }}
path: dist
解释
strategy: 定义构建策略。
matrix: 定义矩阵变量。
node-version: 这是我们选择的变量名称。我们为其分配了一个值数组 [18, 20, 22]。GitHub Actions 将运行 build 任务三次,每次使用一个值。
${{ matrix.node-version }}: 此语法允许你在步骤中访问当前的矩阵值。
完成更改后,保存文件(Ctrl+S 或 Cmd+S)。