Cloudflare Workers 使用 GitHub Actions 部署项目

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

API 需要如下权限

权限分类 权限名 所需权限
帐户 Workers 脚本 编辑
区域 Workers 路由 编辑
用户 用户详细信息 读取
  1. GitHub -> Repo -> Settings -> Secrets and variables -> Actions -> New repository secret 中创建配置。
Name Value 说明
CLOUDFLARE_API_TOKEN 上一步生成 Cloudflare API的授权 Token
  1. package.json 添加部署命令
1
2
3
4
5
6
"scripts": {
"cf:dev": "npx wrangler dev",
"cf:deploy:test": "npx wrangler deploy",
"cf:deploy:pre": "npx wrangler deploy --env pre",
"cf:deploy:prod": "npx wrangler deploy --env prod"
}
  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
name: Deploy to Cloudflare Workers

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 版本

# 安装依赖
- name: Install dependencies
run: npm install --only=prod

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

# 部署到Cloudflare Workers
- name: Deploy to Cloudflare Workers
run: |
# 根据分支选择部署环境
if [ "${{ github.ref }}" == "refs/heads/master" ]; then
DEPLOY_ENV=prod
elif [ "${{ github.ref }}" == "refs/heads/pre" ]; then
DEPLOY_ENV=pre
elif [ "${{ github.ref }}" == "refs/heads/test" ]; then
DEPLOY_ENV=test
else
echo "未知分支,跳过部署!"
exit 1
fi

npm run cf:deploy:$DEPLOY_ENV

评论