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-notesdeploy:
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)
仓库名改为
wangkuowink.github.io部署分支改为 主分支(main)
workflow 修改:
APP_BASE_PATH: /- deploy branch:
main - 删除
repository-name(默认推送当前仓库)
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-token7. 总结
| 项目 | 项目仓库 | 用户主页仓库 |
|---|---|---|
| 仓库名 | 任意 | username.github.io |
| 部署分支 | gh-pages | main |
| Pages URL | https://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 的写权限
