前端 CI/CD 流程是怎样的?如何实现自动化部署?
CI/CD 概念
- CI(持续集成):代码推送后自动构建、测试
- CD(持续交付/部署):自动部署到测试/生产环境
典型前端 CI/CD 流程
代码推送 → 触发 CI → 安装依赖 → 代码检查 → 构建 → 测试 → 部署
↓
测试环境 / 预发布 / 生产GitHub Actions 示例
# .github/workflows/deploy.yml
name: Build and Deploy
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install
run: npm ci
- name: Lint
run: npm run lint
- name: Test
run: npm run test:unit
- name: Build
run: npm run build
env:
VITE_API_URL: ${{ secrets.API_URL }}
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
deploy-staging:
needs: build
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with:
name: dist
path: dist
- name: Deploy to Staging
uses: appleboy/scp-action@v0.1.7
with:
host: ${{ secrets.STAGING_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
source: 'dist/*'
target: '/var/www/staging'
deploy-production:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production # 需要审批
steps:
- uses: actions/download-artifact@v4
with:
name: dist
path: dist
- name: Deploy to CDN
run: |
npx aliyun-cdn-cli deploy --path dist/
env:
CDN_KEY: ${{ secrets.CDN_KEY }}分支策略
main → 自动部署到生产
develop → 自动部署到预发布
feature/* → CI 构建+测试,不部署
hotfix/* → 紧急修复,直接合并 main常用 CI/CD 工具
| 工具 | 特点 |
|---|---|
| GitHub Actions | GitHub 集成、免费额度 |
| GitLab CI | GitLab 集成、自托管 |
| Jenkins | 老牌、自托管、插件多 |
| CircleCI | 云端、速度快 |
| Vercel | 前端友好、零配置 |
| Netlify | 前端友好、零配置 |
Vercel 零配置部署
# 安装 CLI
npm i -g vercel
# 部署
vercel # 预览环境
vercel --prod # 生产环境连接 GitHub 仓库后,推送代码自动部署。
Docker 部署
# Dockerfile
FROM node:20-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]# docker-compose.yml
services:
web:
build: .
ports:
- "80:80"环境变量管理
# .env.development
VITE_API_URL=http://localhost:3000
# .env.staging
VITE_API_URL=https://api.staging.example.com
# .env.production
VITE_API_URL=https://api.example.com构建时注入:npm run build -- --mode staging
最佳实践
- 代码推送即触发 CI
- 测试不通过不部署
- 生产部署需要审批(environment protection)
- 回滚机制:保留历史版本,快速回滚
- 蓝绿部署/灰度发布:降低风险