Cloudflare Pages 使用 GitHub Actions 部署静态网站

  1. 在 Cloudflare后台 -> 配置文件 -> API令牌, 生成 Cloudflare API的授权 Token

API 需要如下权限

权限分类 权限名 所需权限
帐户 Cloudflare Pages 编辑
用户 用户详细信息 读取
  1. GitHub -> Repo -> Settings -> Secrets and variables -> Actions -> New repository secret 中创建配置。
Name Value 说明
CLOUDFLARE_API_TOKEN 上一步生成 Cloudflare API的授权 Token
  1. 在项目根目录下,创建 .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 Cloudflare Pages

on:
push:
branches:
- master # 触发工作流的分支
- pre
- test

jobs:
build-and-deploy:
runs-on: ubuntu-latest

steps:
# 检出代码
- name: Checkout source repository
uses: actions/checkout@v3

# 设置 Node.js 环境
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18.19.0' # 根据你的项目需求选择合适的 Node.js 版本

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

# 安装 wrangler cli
- name: Install wrangler cli
run: npm install -g wrangler

# 安装依赖
- name: Install dependencies
run: pnpm install

# 配置 Cloudflare Token
- name: Set up Cloudflare token
run: |
echo "CLOUDFLARE_API_TOKEN=${{ secrets.CLOUDFLARE_API_TOKEN }}" >> $GITHUB_ENV

# 构建应用并部署到 Cloudflare Pages (for master branch)
- name: Build the app (Production)
if: github.ref == 'refs/heads/master'
run: |
pnpm run build
wrangler pages deploy ./dist --branch main --project-name=production-project-name

# 构建应用并部署到 Cloudflare Pages (for pre branch)
- name: Build the app (Preview)
if: github.ref == 'refs/heads/pre'
run: |
pnpm run build:pre
wrangler pages deploy ./dist --branch main --project-name=preview-project-name

# 构建应用并部署到 Cloudflare Pages (for test branch)
- name: Build the app (Testing)
if: github.ref == 'refs/heads/test'
run: |
pnpm run build:test
wrangler pages deploy ./dist --branch main --project-name=testing-project-name

评论