于 Cloudflare Pages 部署站点

通过本文,你将学习到如何 Cloudflare Pages 上部署站点。

有多种方式将站点部署到 Cloudflare Pages.

通过 Cloudflare Pages 管理面板部署站点

  1. 登录到 Cloudflare 管理面板。
  2. 打开 Pages 页面。
  3. 点击 Create a project 按钮,然后选择 Connect to Git.
  4. 选择仓库并点击 Begin setup
  5. 填写表单。
    1. 输入项目名称,Cloudflare 会给站点分配一个默认域名,显示在输入框下方。
    2. 选择生产分支。
    3. 框架预设置:Hugo。
    4. 构建命令:其取决于你如何安装构建工具,对于新手主题npm ci && hugo --gc --minify --enableGitInfo
    5. 构建输出目录:/public
    6. 环境变量:
      1. HUGO_VERSION:比如 0.111.3
      2. NODE_VERSION:任意大于 16 的版本,如:19

通过 GitHub Cloudflare Pages Actions 部署站点

  1. 通过 Cloudflare Pages 管理面板 创建站点,并关闭其自带的自动部署。
  2. 创建 CLOUDFLARE_ACCOUNT_ID1CLOUDFLARE_API_TOKEN2 action’s secrets
  3. 创建以下工作流程,并按需修改配置。
  4. projectName 替换为你的站点名称。
.github/workflows/cloudflare-pages.yaml
 1name: Cloudflare Pages
 2
 3on:
 4  # auto deploy when pushing to specified branches.
 5  push:
 6    branches:
 7      - main
 8
 9  # allow triggering workflow manually.
10  workflow_dispatch:
11
12jobs:
13  publish:
14    runs-on: ubuntu-latest
15    permissions:
16      contents: read
17      deployments: write
18    name: Publish to Cloudflare Pages
19    steps:
20      - name: Checkout
21        uses: actions/checkout@v3
22
23      - name: Setup Node
24        uses: actions/setup-node@v3
25        with:
26          node-version: "19"
27
28      - name: Cache dependencies
29        uses: actions/cache@v3
30        with:
31          path: ~/.npm
32          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
33          restore-keys: |
34            ${{ runner.os }}-node-            
35
36      - name: Install dependencies
37        run: npm ci
38
39      - name: Setup Hugo
40        uses: peaceiris/actions-hugo@v2
41        with:
42          hugo-version: "latest"
43          extended: true
44
45      - name: Cache Hugo modules
46        uses: actions/cache@v3
47        with:
48          path: /tmp/hugo_cache
49          key: ${{ runner.os }}-hugomod-${{ hashFiles('**/go.sum') }}
50          restore-keys: |
51            ${{ runner.os }}-hugomod-            
52
53      - name: Build
54        run: hugo --minify --gc --enableGitInfo
55        # Use following instead if defaultContentLanguageInSubdir is enabled.
56        # run: hugo --minify --gc --enableGitInfo && cp public/en/404.html public/404.html
57
58      - name: Publish to Cloudflare Pages
59        uses: cloudflare/pages-action@v1
60        with:
61          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
62          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
63          projectName: hb-theme
64          directory: ./public
65          # Optional: Enable this if you want to have GitHub Deployments triggered
66          gitHubToken: ${{ secrets.GITHUB_TOKEN }}

  1. 详情请参阅 Get account ID。 ↩︎

  2. 另请参阅 Generate an API token。 ↩︎