将 vuepress 部署到 github pages

762 阅读1分钟

  捣鼓了一整天总算是搞好了,在 username.github.io 仓库中的 main 分支放 vuepress 项目代码,gh-pages 分支放打包后的文件,每次 push 到 main 分支后自动打包部署到 gh-pages 分支,写一些踩坑记录。

1. deploy.sh

项目中写一个 deploy.sh 脚本,负责 build 并将打包后的 dist 推送到 gh-pages 分支,推送时需要用到 ACCESS_TOKEN;注意在 dist 中的默认分支是 master,git push 最后的参数表示将本地 master 分支推送到远程仓库的 gh-pages 分支上,之前没留意写成了 main 分支就报错了。

#!/usr/bin/env bash
set -e
yarn build
cd docs/.vuepress/dist

git config --global user.email "719887163@qq.com"
git config --global user.name "xiaohj"
git init
git add -A
git commit -m 'deploy'
git push -f https://${ACCESS_TOKEN}@github.com/xia0hj/xia0hj.github.io.git master:gh-pages

cd -

2. ACCESS_TOKEN

上面用的 ACCESS_TOKEN 需要在个人设置里生成

  1. 进入 github 点击右上角头像,点击 Settings -> Developer settings -> Personal access tokens -> Generate new token。
  2. 勾选 repo 后生成 token,复制下来。
  3. 进入 username.github.io 仓库,点击 Settings -> Secrets -> Actions -> New repository secret。
  4. Name 设为 ACCESS_TOKEN,Value 就填 token。

3. 创建 workflow

  1. 进入 username.github.io 仓库,点击 Actions -> New workflow 创建新的 workflow。
  2. workflow 在 push 到 main 分支时触发,执行 yarn 安装依赖,然后执行 deploy.sh 脚本。
  3. 可缓存 yarn 减少部署时间,参考 github.com/actions/cac…
  4. 安装依赖时要执行 yarn --prefer-offline 优先使用缓存,详见 stackoverflow.com/questions/6…
  5. 执行 deploy.sh 脚本时需要将项目的 ACCESS_TOKEN 作为参数传递给脚本,env: ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
  6. 以下是我的 workflow.yml
name: deploy after push
on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Get yarn cache directory path
        id: yarn-cache-dir-path
        run: echo "::set-output name=dir::$(yarn cache dir)"

      - uses: actions/cache@v3
        id: yarn-cache
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install dependencies
        run: yarn --prefer-offline
        
      - name: Run deploy.sh
        env:
          ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
          BRANCH: gh-pages
        run: yarn deploy

4. 设置 github pages

  1. 进入 username.github.io 仓库,点击 Settings -> Pages。
  2. 将 Branch 修改为 gh-pages。

5. 查看执行情况

  push 到 main 分支后,可在仓库的 Actions 中查看执行情况,如果像我这样看不到 log 可能是网络问题,换了 VPN 节点之后就能看到了。

image.png