全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-23 7 分钟 ✍️ juanwangdev

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 条件减少无效构建
  • 并行构建减少总耗时
  • 分阶段部署实现安全发布

📝 发现内容有误?点击此处直接编辑

← 上一篇 微前端架构概述
下一篇 → CDN 部署与资源分发
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库