CI/CD (GitHub Actions / GitLab CI)

1. 面试题

Q: 如果让你配置一个 CI/CD 流程,需要包含哪几个步骤?gitlab-ci.yml 怎么写?

2. 核心解答

CI/CD (持续集成 Continuous Integration / 持续部署 Continuous Deployment) 是现代工程化的 基石。 它通过 Pipeline (流水线),把从代码提交到上线发布的全过程自动化,减少人工干预和出错。

(1) 标准流程 (Standard Pipeline)

  • Install Dependencies (预装依赖):node_modules 安装。
  • Lint (代码检查):Eslint / Prettier。
  • Test (自动化测试):Unit Test (Jest), E2E Test (Cypress)。
  • Build (构建打包):npm run build 生成 dist 产物。
  • Preview (预览):如果是 Pull Request,部署到临时环境 (Vercel/Netlify)。
  • Release (发布):如果是 main 分支,升级版本号 (npm version),生成 Tag,部署到生产环境 (S3/CDN/Docker)。

(2) GitHub Actions (.github/workflows/main.yml)

name: CI
on:
  push:
    branches: [ main ]  # 触发条件

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3  # 拉代码
    
    - name: Setup Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
        cache: 'npm'  # 缓存 node_modules,极快加速

    - run: npm ci  # 干净安装依赖 (Strict)
    - run: npm run lint
    - run: npm run test
    - run: npm run build

    - name: Deploy to GitHub Pages
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./dist

(3) GitLab CI (.gitlab-ci.yml)

stages:
  - install
  - test
  - build
  - deploy

cache:
  paths:
    - node_modules/  # 缓存依赖

install_dependencies:
  stage: install
  script:
    - npm ci

unit_test:
  stage: test
  script:
    - npm run test

build_app:
  stage: build
  script:
    - npm run build
  artifacts:
    paths:
      - dist/  # 传递构建产物到下一个 stage

deploy_prod:
  stage: deploy
  only:
    - main  # 只有主分支才部署
  script:
    - scp -r dist/* user@server:/var/www/html

3. 面试加分项

Q: 为什么用npm ci 而不是npm install

在 CI 环境中,确定性 (Deterministic) 至关重要。 npm install 可能会根据 package.json 更新某些依赖的小版本,导致和本地开发环境不一致。 npm ci (Clean Install) 严格遵循 package-lock.json,如果 lock 文件和 package.json 不匹配会直接报错,并且会先删除 node_modules 确保干净安装。且速度通常比 npm install 快。

4. 总结

  • Pipeline: Lint -> Test -> Build -> Deploy.
  • Cache: Use cache for node_modules.
  • Install: Use npm ci.
  • Artifact: Pass build output between jobs.