多个Github Pages设置

概述

  • GitHub Pages分为: 用户/组织主页以及项目主页
  • 用户主页或组织主页分别都只能存在一个repo,而项目主页则没有repo数量限制
  • 若要发布用户主页,必须创建名为<username>.github.io的repo; 若要发布组织主页,必须创建名为<organization>.github.io的repo; 而项目主页的仓库则没有名称限制
  • 用户主页默认域名形式为<username>.github.io
  • 组织主页默认域名形式为<organization>.github.io
  • 项目主页默认域名形式为<username>.github.io/<repository>或者<organization>.github.io/<repository>
  • 用户主页或组织主页的展示内容以主分支(master分支或main分支)里的文件为准;而项目主页的展示内容以gh-pages分支内的文件为准

示例

以部署一个VuePress项目主页为例

  1. 参考VuePress指南在本地建立好项目
  2. 建立一个Github仓库,取名任意
  3. 参考VuePress部署部署项目到Github上
    • 注意在配置文件中设置正确的base选项,在该示例中base应为第2步建立的仓库名
    • 编写GitHub Actions工作流
    • 推送本地仓库到GitHub远程仓库
    • 进入GitHub项目仓库找到Settings下的Pages,修改Build and deployment下的branch选项为gh-pages(此操作会触发GitHub Actions进行重新部署)
  4. 访问部署好的页面(Github项目仓库的Settings下的Pages页面可以看到)

GitHub Actions工作流参考

在本地项目根目录下新建.github/workflows/docs.yml文件来设置工作流 下面的工作流示例和VuePress官方写的工作流写的略有不同,官方使用的pnpm作为包管理器,而工作流示例直接使用Node.js自带的npm,而且新增一步安装vuepress@next依赖(针对使用VuePrss 2.x版本), 构建脚本步骤也进行了修改

name: Build and Deploy

on:
  # 每当 push 到 main 分支时触发部署
  push:
    branches: [main]
  # 手动触发部署
  workflow_dispatch:

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout 
        uses: actions/checkout@v3
        with:
          # “最近更新时间” 等 git 日志相关信息,需要拉取全部提交记录
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          # 选择要使用的 node 版本
          node-version: 16
          # 缓存 npm 依赖
          cache: npm

      # 安装VuePress(基于VuePress 2.x)
      - name: Install VuePress
        run: npm install -D vuepress@next

      # 运行构建脚本(使用npm命令)
      - name: Build VuePress site
        run: npm run docs:build

      # 查看 workflow 的文档来获取更多信息
      # @see https://github.com/crazy-max/ghaction-github-pages
      - name: Deploy to GitHub Pages
        uses: crazy-max/ghaction-github-pages@v2
        with:
          # 部署到 gh-pages 分支
          target_branch: gh-pages
          # 部署目录为 VuePress 的默认输出目录
          build_dir: docs/.vuepress/dist
        env:
          # @see https://docs.github.com/cn/actions/reference/authentication-in-a-workflow#about-the-github_token-secret
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}