於 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。 ↩︎