SPA单页应用 (Vue/React) 通过GitHub Actions部署到Netlify

目标:

  1. 项目源代码放到Github私有仓库上(在个人账户和在组织账户均可);

  2. 项目代码推送到特定分支后,通过GitHub Actions自动构建并发布,并根据不同环境执行不同的打包命令;

  3. 项目部署在Netlify上,不同环境发布到Netlify的不同站点上。

步骤

  1. 在 Netlify 上的 User settings -> Applications -> OAuth -> Personal access tokens 下生成一个新的 access tokens

  2. 在 Netlify 上针对不同环境创建不同的站点,选择手动部署,然后进入站点配置中,在 Site configuration -> General -> Site details -> Site information 拿到需要发布的站点的 Site ID,注意不是 Site name

  3. GitHub -> Repo -> Settings -> Secrets and variables -> Actions -> New repository secret 中创建配置。

Name Value 说明
NETLIFY_AUTH_TOKEN 第一步创建的 access tokens
NETLIFY_SITE_ID_TEST 测试分支需要发布的 Site ID
NETLIFY_SITE_ID_PROD 生产分支需要发布的 Site ID
  1. 在 Vue/React 项目根目录下,创建 .github/workflows/deploy.yml 文件,用来配置使用Github Actions触发自动构建,示例配置文件内容如下:

    (注:根据自己项目的情况,选择构建的Node版本以及打包编译命令,添加更多的环境等)

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
name: Deploy to Netlify

on:
push:
branches:
- master # 当推送到 master 分支时触发部署
- test # 当推送到 test 分支时触发部署

jobs:
build:
runs-on: ubuntu-latest
steps:
# Checkout code
- name: Checkout repository
uses: actions/checkout@v3

# Set up Node.js
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18.19.0' # 使用指定的 Node 版本

# Install pnpm
- name: Install pnpm
run: npm install -g pnpm

# Install dependencies
- name: Install dependencies
run: pnpm install

# Build the app (for master branch)
- name: Build the app (Production)
if: github.ref == 'refs/heads/master'
run: pnpm run build # Production build command

# Build the app (for test branch)
- name: Build the app (Testing)
if: github.ref == 'refs/heads/test'
run: pnpm run build:test # Testing (test) build command

# Deploy to Netlify (for master branch)
- name: Deploy to Netlify (Production)
if: github.ref == 'refs/heads/master' # 只在推送到 master 分支时部署
uses: nwtgck/actions-netlify@v1
with:
publish-dir: './dist' # Vue 项目的构建输出目录
production-branch: master
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_PROD }} # 使用生产环境的 Netlify Site ID

# Deploy to Netlify (for test branch)
- name: Deploy to Netlify (Testing)
if: github.ref == 'refs/heads/test' # 只在推送到 test 分支时部署
uses: nwtgck/actions-netlify@v1
with:
publish-dir: './dist' # Vue 项目的构建输出目录
production-branch: test # 使用 test 分支进行部署
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_TEST }} # 使用测试环境的 Netlify Site ID
  1. 结束,这个时候你提交代码到仓库对应分支就会自动构建并发布到对应环境的Netlify站点上了。

评论