CI/CD 构建流水线优化
优化 CI/CD 流水线减少构建时间,加速部署周期。
基础 CI 配置
YAML
# GitHub Actions
name: Build and Deploy
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'npm'
- name: Install
run: npm ci
- name: Build
run: npm run build
- name: Deploy
run: aws s3 sync dist s3://bucket --delete
依赖缓存优化
YAML
- name: Cache npm
uses: actions/cache@v3
with:
path: ~/.npm
key: npm-${{ hashFiles('package-lock.json') }}
restore-keys: npm-
- name: Cache node_modules
uses: actions/cache@v3
with:
path: node_modules
key: modules-${{ hashFiles('package-lock.json') }}
注意:缓存依赖减少每次构建的安装时间。
Vite 缓存优化
YAML
- name: Cache vite deps
uses: actions/cache@v3
with:
path: node_modules/.vite
key: vite-${{ hashFiles('package-lock.json') }}
并行构建优化
YAML
jobs:
build:
strategy:
matrix:
shard: [1, 2, 3, 4]
steps:
- name: Build shard
run: npm run build -- --shard ${{ matrix.shard }}
构建时间对比
| 优化项 | 时间减少 | |
|---|---|---|
| 依赖缓存 | -60% | |
| Vite 缓存 | -30% | |
| 并行构建 | -40% |
条件触发优化
YAML
on:
push:
branches: [main]
paths:
- 'src/**' # 源码变化触发
- 'package.json' # 依赖变化触发
- 'vite.config.js' # 配置变化触发
避免无关文件变化触发构建。
构建产物缓存
YAML
- name: Cache build
uses: actions/cache@v3
with:
path: dist
key: build-${{ github.sha }}
- name: Build if no cache
run: |
if [ ! -d "dist" ]; then
npm run build
fi
分阶段部署
YAML
jobs:
build:
# 构建阶段
deploy-staging:
needs: build
# 预发布环境部署
deploy-production:
needs: deploy-staging
if: github.ref == 'refs/heads/main'
# 生产环境部署
构建优化策略
| 策略 | 效果 | |
|---|---|---|
| 缓存依赖 | 减少安装时间 | |
| 条件触发 | 减少无效构建 | |
| 并行构建 | 减少总耗时 | |
| 分阶段部署 | 安全发布 |
要点总结
- 缓存依赖和 Vite 预构建产物
- paths 条件减少无效构建
- 并行构建减少总耗时
- 分阶段部署实现安全发布
📝 发现内容有误?点击此处直接编辑