使用Hugo创建网站并且通过GitHub Actions持续集成与Cloudflare Pages自动部署这种方法结合了GitHub Actions的构建能力和Cloudflare Pages的托管服务,实现了Hugo网站的高效、自动化部署流程。主要优势包括:

  1. 构建流程控制:通过GitHub Actions完全自定义Hugo站点的构建步骤
  2. 灵活性:可以在构建过程中添加额外的预处理或检查步骤
  3. 版本管理:直接与GitHub仓库集成,实现代码和内容的版本追踪

关键实现步骤:

  • 在GitHub仓库中配置工作流文件
  • 使用Cloudflare Pages的部署Action
  • 设置必要的构建和部署环境变量

这种方法不仅提供了更精细的构建控制,还能保证部署的一致性和可靠性。

on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    env:
      HUGO_VERSION: 0.128.0
    steps:
      - name: Install Hugo CLI
        run: |
          wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb \
          && sudo dpkg -i ${{ runner.temp }}/hugo.deb          
      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: recursive
      - name: Build with Hugo
        env:
          HUGO_CACHEDIR: ${{ runner.temp }}/hugo_cache
          HUGO_ENVIRONMENT: production
        run: |
          hugo --minify          
      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: my-project
          path: ./public
  deploy:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write
    name: Deploy to Cloudflare Pages
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: my-project
          path: ./public
      - name: Verify build output
        run: |
          if [ ! -d "./public" ] || [ -z "$(ls -A ./public)" ]; then
            echo "Build output is empty. Please check your Hugo configuration or content.";
            exit 1;
          fi          
      - name: Publish
        uses: cloudflare/pages-action@v1
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          projectName: my-project # e.g. 'my-project'
          directory: ./public # e.g. 'dist'
          gitHubToken: ${{ secrets.GITHUB_TOKEN }}