CI 缓存、并行任务和失败产物
🔄 好的 CI 配置能将流水线执行时间从 10 分钟压到 2 分钟。缓存、并行化和失败产物是三大丝。
构建缓存
Node modules 缓存
# GitHub Actions 示例
- name: Cache node modules
uses: actions/cache@v4
with:
path: ~/.npm # 或 node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
Vite/Turborepo 缓存
- name: Cache Vite build
uses: actions/cache@v4
with:
path: |
node_modules/.vite
.turbo
key: ${{ runner.os }}-vite-${{ hashFiles('src/**') }}
缓存命中率技巧
key精确匹配,restore-keys作为备选匹配- 包含易变内容的文件哈希(如 package-lock.json)
- 不同 平台(OS)必须分开缓存 key
任务并行化
jobs:
test:
strategy:
matrix:
node-version: [18, 20, 22]
max-parallel: 3
fail-fast: false # 一个失败不停止其他
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm test
任务依赖与并行
jobs:
lint: runs-on: ubuntu-latest
test: runs-on: ubuntu-latest
build: needs: [lint, test] # 并行 lint + test 后才 build
deploy: needs: [build] # build 完成才 deploy
失败产物
- name: Run tests
run: npm test
- name: Upload test results on failure
if: failure() # 只在失败时上传
uses: actions/upload-artifact@v4
with:
name: test-results-${{ github.run_id }}
path: |
coverage/
playwright-report/
test-results/
retention-days: 7 # 保留 7 天
- name: Upload Playwright trace on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-traces
path: test-results/**/*.zip
常用 CI 模式
完整前端 CI 流水线
name: CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: 'npm' }
- run: npm ci
- run: npm run type-check
- run: npm run lint
- run: npm run test:unit -- --coverage
e2e:
runs-on: ubuntu-latest
needs: quality
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: 'npm' }
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npm run test:e2e
- if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
常见误区
- 每次都重新安装 node_modules 而没有缓存,流水线正常 CI 5+ 分钟
- 所有任务串行执行,没有利用 needs 并行化
- 失败时没有保留产物,调试 CI 失败时无屏可查