Skip to content

GitHub Pages 部署与 Workflow

1. GitHub Actions 构建与部署 workflow

示例 workflow(项目仓库)

yaml
name: GitHub Actions Build and Deploy

on:
  push:
    branches: [main]
  workflow_dispatch:
  repository_dispatch:
    types: [build-and-deploy]

permissions:
  contents: write

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: true

      - uses: pnpm/action-setup@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - run: |
          pnpm install
          pnpm run build
        env:
          APP_BASE_PATH: /wk-notes

      - run: cp README.md ./dist/

      - name: Deploy
        uses: JamesIves/github-pages-deploy-action@v4
        with:
          branch: gh-pages
          folder: dist
          token: ${{ secrets.GITHUB_TOKEN }}
          clean: true

注意事项

  • fetch-depth: 0 + persist-credentials: true 确保 token 注入。
  • gh-pages 分支用于项目仓库部署。
  • APP_BASE_PATH 对应项目路径(根路径 //repo-name)。

4. 跨仓库触发 workflow

  • 在另一个仓库 daily-notes 创建 issue 时触发 wk-notes deploy:
yaml
- uses: peter-evans/repository-dispatch@v3
  with:
    token: ${{ secrets.ACCESS_TOKEN }}  # PAT
    repository: ${{ secrets.REPOSITORY }} # wangkuowink/wk-notes
    event-type: build-and-deploy

注意

  • ACCESS_TOKEN 必须是 个人访问 token (PAT),并有 repo 权限。
  • GITHUB_TOKEN 不能跨仓库触发 workflow
  • repository 必须是目标仓库全名。
  • client-payload 可选,可以传额外信息给目标 workflow。

5. 用户主页仓库部署(wangkuowink.github.io)

  1. 仓库名改为 wangkuowink.github.io

  2. 部署分支改为 主分支(main)

  3. workflow 修改:

    • APP_BASE_PATH: /
    • deploy branch: main
    • 删除 repository-name(默认推送当前仓库)
  4. Pages URL:

https://wangkuowink.github.io/
  • 用户主页仓库无需 gh-pages 分支,主分支就是 Pages 源。

6. token 权限判断

  • workflow 顶部声明:
yaml
permissions:
  contents: write
  • 仓库 Settings → Actions → General → Workflow permissions → “Read and write”
  • 临时测试 push:
yaml
- run: |
    git checkout -b test-token
    touch test.txt
    git add test.txt
    git commit -m "Test token write"
    git push origin test-token

7. 总结

项目项目仓库用户主页仓库
仓库名任意username.github.io
部署分支gh-pagesmain
Pages URLhttps://username.github.io/repo-name/https://username.github.io/
APP_BASE_PATH/repo-name/

8. 小结

通过以上步骤,可以实现:

  • 配置 GitHub Actions 自动构建与部署
  • 跨仓库触发 workflow(通过 PAT + repository_dispatch)
  • 将项目仓库迁移为用户主页仓库部署,URL 和路径正确
  • 判断和测试 GITHUB_TOKEN 或 PAT 的写权限

转载或 CV 自 maomao1996