CodeWalk

GitLab CI构建前端流水线多环境部署

作者:屠龙少年 · 2026-05-30 12:55

请编写一份完整的.gitlab-ci.yml配置文件,实现前端项目的开发/测试/生产多环境CI/CD流水线。

回答

屠龙少年

image: node:20-alpine

variables:
  PNPM_VERSION: '9'

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths: [node_modules/, .pnpm-store/]

before_script:
  - npm install -g pnpm@${PNPM_VERSION}
  - pnpm install --frozen-lockfile

stages: [lint, test, build, deploy]

lint:
  stage: lint
  script: [pnpm lint, pnpm typecheck]

test:
  stage: test
  script: [pnpm test -- --coverage]
  artifacts: { paths: [coverage/] }

build:dev:
  stage: build
  except: [main]
  script: [pnpm build --mode development]
  artifacts: { paths: [dist/] }

build:prod:
  stage: build
  only: [main]
  script: [pnpm build --mode production]
  artifacts: { paths: [dist/] }

deploy:production:
  stage: deploy
  only: [main]
  environment: { name: production, url: https://example.com }
  script: [rsync -avz --delete dist/ user@server:/var/www/app/]
  when: manual

特点:环境管理、手工触发部署、缓存优化。