从零搭建 CI/CD 流水线

每次提交代码后手动构建、手动部署,既繁琐又容易出错。CI/CD 流水线能把这些重复劳动自动化:你只需 push 代码,系统就会自动完成检查、测试、构建和发布。GitHub Actions 是目前门槛最低、与代码仓库集成最紧密的方案,本文将以它为例,带你从零搭建一套前端 CI/CD 流水线。

CI/CD 概念

CI/CD 是两个阶段的组合:

  • 持续集成(CI):每次提交自动运行 lint、测试、构建,尽早发现问题
  • 持续部署(CD):构建通过后自动部署到测试或生产环境,缩短交付周期

两者的目标都是让代码从提交到上线的过程「快且可靠」。

GitHub Actions 基础

GitHub Actions 的核心是 workflow 文件,放在仓库的 .github/workflows/ 目录下,使用 YAML 描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
name: CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "Hello CI"

on 定义触发时机,jobs 定义任务,steps 是任务内的执行步骤。uses 引用官方或社区的 Action,run 执行普通 shell 命令。

前端 CI 流水线

一个标准的前端 CI 流程包含安装依赖、代码检查、测试和构建:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
jobs:
ci:
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 dependencies
run: npm ci

- name: Lint
run: npm run lint

- name: Test
run: npm test

- name: Build
run: npm run build

npm cinpm install 更快更严格,适合 CI 环境。任何一步失败都会中断流水线,防止有问题的代码进入下一阶段。

自动部署到 GitHub Pages

构建通过后,用一个独立的 deploy job 将产物发布到 GitHub Pages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
deploy:
needs: ci
runs-on: ubuntu-latest
permissions:
contents: read
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build

- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./public

- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

needs: ci 确保只有 CI 通过才部署,permissions 授予 Pages 写入权限。配置完成后,每次合并到 main 分支就会自动上线。

缓存优化

CI 的最大开销在于重复安装依赖。利用 actions/setup-nodecache: npm 可缓存 npm 全局目录,二次构建能快上数倍。此外可缓存 node_modules 或构建产物,用 actions/cache 配合唯一 key 实现:

1
2
3
4
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}

package-lock.json 未变时命中缓存,跳过重新下载。

通知与集成

流水线运行结果应及时通知团队。通过 webhook 可将构建状态推送到 Slack、钉钉或飞书:

1
2
3
4
5
6
- name: Notify on failure
if: failure()
run: |
curl -X POST ${{ secrets.WEBHOOK_URL }} \
-H 'Content-Type: application/json' \
-d '{"text":"CI 构建失败,请检查!"}'

if: failure() 保证仅在失败时触发,避免成功消息打扰。

总结

一套完整的 CI/CD 流水线,能让团队专注于写代码,把检查、构建、部署交给机器。从 GitHub Actions 入门,逐步加入缓存优化和通知集成,你会发现交付效率与代码质量都在同步提升。当自动化成为习惯,发布新版本就不再是令人紧张的事件,而是一次平淡的 push。