GitHub Actions
GitHub 内置的工作流自动化。
3 小时
GitHub Actions
这一课你将能做到
- 编写 GitHub Actions 工作流
- 实现 CI(自动测试、构建)
- 实现 CD(自动部署到服务器)
为什么要学
手动部署容易出错:忘测试、环境不一致、版本混乱。GitHub Actions 在代码提交后自动执行测试、构建、部署,保证每次发布质量一致。
人话:GitHub Actions 是「机器人」,代码一提交就自动帮你测试、打包、上线。
跟着做
步骤 1:基础工作流
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build
步骤 2:矩阵测试(多版本)
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16, 18, 20]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm test
步骤 3:自动部署
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
needs: test # 等 test 通过
steps:
- uses: actions/checkout@v3
- name: Deploy to server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /var/www/app
git pull origin main
npm install --production
npm run build
pm2 restart app
步骤 4:缓存加速
steps:
- uses: actions/checkout@v3
- name: Cache node_modules
uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- run: npm ci
步骤 5:环境变量与 Secrets
env:
NODE_ENV: production
jobs:
deploy:
steps:
- run: echo "${{ secrets.API_KEY }}"