Hexo 添加 Github Action 工作流

在中国大陆地区的 GitHub 的连接不稳定,强烈建议操作环境开启网络代理再进行下列操作!!!

需要用到工具

新建 GitHub 仓库

登录好 Github 账号,在首页左上角点击绿色的 new 选项

填写 Git 仓库信息

确认好信息之后,点击Create repository

仓库创建完成会显示如下信息:

红色的方框里面将 SSH 切换到 HTTPS 并且记录好红色方框里面的链接,往下的步骤需要用到

推送源码到 Git 仓库

通过 VS Code 打开博客根目录。如下图步骤打开CMD终端

通过终端依次输入下列代码将代码推送至 Git 仓库。

1
2
3
4
5
6
7
8
9
# 安装 hexo 部署到 git page 的 deployer
npm install hexo-deployer-git --save

git init # Gti 初始化
git remote add origin https://github.com/yourusername/your-repo.git # 这里替换创建的 Git 仓库链接
git add .
git commit -m "Initial commit"
git branch -M main
git push -u origin main

执行完成之后可以回到网页端查看是否成功。成功推送如下图:

创建并配置 Token

创建 Token

点击个人头像 —— Settings —— Developer settings —— Tokens(classic) —— Generate new token —— Generate new token(classic)

配置 Token 权限

填写好 Token 名称
Expiration 中选择 No xpiration
Select scopes列表中,将 repoworkflow 打勾

确认好之后拉到最底下点击 Generate token 完成 Token 的创建,并且记住 Token
这个 Token 是给 Github Action 用的,Github Action 会把 Hexo 编译部署到 gh-pages 分支。

配置 Git 仓库 Token

打开创建的 Git 仓库 —— Settings —— Secrets and variables —— New repository secret

Name 下面的方框里面输入 GH_TOKEN
Secret 下面的方框里面输入创建的 Token

输入完毕确认无误之后,点击 Add secret

修改_config.yml

在 _config.yml 中修改 deploy 字段。指示 Hexo 在 deploy 时的推送地址

1
2
3
4
deploy:
type: git
repo: https://github.com/yourusername/your-repo.git # 这里替换创建的 Git 仓库链接
branch: gh-pages

配置Github Action工作流

在博客根目录 .github 文件夹下新增 workflows 文件夹,然后新增 deploy.yml 文件,里面有个 node-version 要和你本地的 Node.js 一致。
如果不确定本地安装的 Node.js 版本是多少,可以在 VS Code 终端或者本地终端里面输入 node -v 查看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
name: Deploy Hexo to GitHub Pages

on:
push:
branches:
- main # 当推送到 main 分支时触发

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
submodules: false # 禁用子模块检查

- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '22' #更换对应的node版本

- name: Install Dependencies
run: npm install

- name: Install Hexo Git Deployer
run: |
npm install hexo-deployer-git --save
npm install hexo-cli -g

- name: Clean and Generate Static Files
run: |
hexo clean
hexo generate

- name: Configure Git
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'

- name: Deploy to GitHub Pages
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
run: |
cd public/
git init
git add -A
git commit -m "Create by workflows"
git remote add origin https://${{ secrets.GH_TOKEN }}@github.com/yourusername/your-repo.git
git push origin HEAD:gh-pages -f

步骤大致意思就是使用 ubuntu-latest 作为基础环境,然后安装各种依赖,随后 hexo generate 生成博客网站静态文件夹,把这个文件夹推送到同一仓库的 gh-pages 分支

推送测试

VS Code 左侧边栏中点击第三个选项(源代码管理),点击下箭头选择提交和推送

弹出的窗口里面编辑好修改的日志并且保存,右上角打勾即可晚上源码修改推送

打开 Git 仓库 Actions 里面查看工作流成功运行便大功告成

结尾

之后的每次对博客的修改,在本地确认无误之后,都需要重新执行一次源码上传的操作来同步更改,而 Github Action 工作流则自动在云端完成
有了这个源码仓库,就可以使用 Cloudflare PagesEdgeOne pages 等免费部署云端博客