使用GitHub Actions自动部署Hexo博客

发布时间 2023-10-15 12:02:30作者: l4y

准备两个仓库

  • 源码库:hexo源码仓库
  • 网页库:{username}.github.io

目标

在源码库编写博客,推送到远端后,触发 Github Actions。Actions 配置 hexo 环境,生成 hexo 文件后,推送到网页库。

推送网页到网页库的权限问题,通过 Github 的 access token 解决(https://github.com/settings/tokens)。

需要将上述 token 配置在源码库的 Settings->Secrets->Action 中。

xjshi/hexo-deploy-github-pages-action@master 基于开源的 Actions 做了一些修改,在源码库中调用该 Actions 即可。

具体如下:

name: 部署 GitHub Pages
on:
  push:
    branches:
      - master # 源码库的分支,该分支有提交时,就出发该action

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@master

      - name: Build and Deploy
        # 使用专门部署 Hexo 到 GitHub pages 的 action(可以fork后根据需要修改)
        uses: xjshi/hexo-deploy-github-pages-action@master
        env:
          PERSONAL_TOKEN: ${{ secrets.GENERATE_HEXO_STATIC_FILES }} # secret 名,需要跟源码库设置中添加的secret名一致。
          PUBLISH_REPOSITORY: username/username.github.io # 网页库,格式:用户名/仓库名
          BRANCH: master # 构建后的网页要推送到网页库的分支
          PUBLISH_DIR: ./public # 部署 public 目录下的文件,hexo 一般都是这个目录,可根据实际调整