GitHub Actions CI 笔记
GitHub Actions CI 笔记
CI 的目标是让项目每次提交后自动检查。最基础的 CI 不需要很复杂,只要能跑格式化、lint、测试和构建,就已经能挡住很多低级问题。
工作流文件位置
GitHub Actions 的配置放在:
.github/workflows/*.yml
例如:
.github/workflows/ci.yml
一个 Node 项目的基础 CI
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build
npm ci 比 npm install 更适合 CI,因为它严格按 lockfile 安装。
常见触发方式
-
push:推送到指定分支时触发。 -
pull_request:提交 PR 时触发。 -
workflow_dispatch:允许手动触发。 -
schedule:定时任务。
加缓存
actions/setup-node 自带 npm 缓存能力:
with:
node-version: 20
cache: npm
这能减少重复下载依赖的时间。
分支保护
CI 真正有用,需要和分支保护配合:
- main 分支禁止直接 push。
- PR 必须通过 CI。
- 至少一个 reviewer approve。
否则 CI 只是提示,不会真正阻止坏代码进入主分支。
排错思路
CI 失败时先看第一处报错,不要只看最后一行。常见原因包括依赖版本不一致、环境变量缺失、测试依赖本地文件、脚本在 Linux 下路径大小写错误。
Enjoy Reading This Article?
Here are some more articles you might like to read next: