Hexo 生成的是静态文件,传统做法是本地 hexo g -d 推送到 Pages 仓库。有了 GitHub Actions 后,每次 git push 源码仓库就能自动构建部署,解放本地环境。

本文记录完整的配置流程。

整体思路

两个仓库分工:

  • 源码仓库jeromexiong/blog)— 存 Hexo 源码、文章、主题配置
  • Pages 仓库jeromexiong/jeromexiong.github.io)— 存构建产物(public/ 目录),GitHub Pages 从这读取

CI/CD 要做的就是:源码仓库收到 push → 自动构建 → 推送到 Pages 仓库。

一、生成 SSH Deploy Key

为了让 GitHub Actions 有权限写入 Pages 仓库,需要一对 SSH 密钥。公钥给 Pages 仓库,私钥给源码仓库。

1
ssh-keygen -t ed25519 -f ~/blog-deploy-key -N "" -C "deploy"

这会生成两个文件:

  • blog-deploy-key — 私钥
  • blog-deploy-key.pub — 公钥

二、配置 GitHub

添加 Deploy Key(Pages 仓库)

  1. 打开 https://github.com/jeromexiong/jeromexiong.github.io/settings/keys
  2. Add deploy key
  3. Title: Blog CI/CD
  4. Key: 粘贴 blog-deploy-key.pub 的内容
  5. Allow write access: ✅ 务必勾上
  6. Add key

添加 Secret(源码仓库)

  1. 打开 https://github.com/jeromexiong/blog/settings/secrets/actions
  2. New repository secret
  3. Name: DEPLOY_KEY
  4. Secret: 粘贴 blog-deploy-key(私钥)的全部内容
  5. Add secret

三、编写 Workflow 文件

在源码仓库创建 .github/workflows/deploy.yml

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
name: Deploy Blog

on:
push:
branches: [master]
workflow_dispatch:

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

- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: package-lock.json

- name: Install dependencies
run: npm ci

- name: Generate static files
run: npx hexo generate

- name: Deploy to jeromexiong.github.io
uses: peaceiris/actions-gh-pages@v4
with:
deploy_key: ${{ secrets.DEPLOY_KEY }}
external_repository: jeromexiong/jeromexiong.github.io
publish_dir: ./public
publish_branch: master
force_orphan: true

关键点说明:

配置项 含义
branches: [master] 只在 master 分支推送时触发
workflow_dispatch 支持在 GitHub 页面手动触发
peaceiris/actions-gh-pages 社区成熟的 Pages 部署 Action
deploy_key 引用上一步配的 Secret
force_orphan: true 每次都生成独立 commit,保持产物仓库干净

四、Dependabot 自动更新依赖

除了部署自动化,还可以通过 Dependabot 让依赖保持最新,避免 Hexo 插件因版本过旧产生安全漏洞或兼容问题。

在仓库创建 .github/dependabot.yml

1
2
3
4
5
6
7
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 20

配置说明:

配置项 含义
package-ecosystem: npm 监控 npm 依赖(package.json)
interval: daily 每天检查一次更新
open-pull-requests-limit: 20 最多同时开 20 个更新 PR

Dependabot 每天自动检查依赖是否有新版本,有更新就提 PR。CI/CD 工作流会在 PR 上自动跑构建验证,通过后手动合并即可。依赖安全和自动部署就形成了一个完整的闭环。

五、推送触发

把 workflow 文件和私钥保护配置一起提交:

1
2
3
4
5
6
# 确保私钥不被提交到仓库
echo ".deploy-key" >> .gitignore

git add .gitignore .github/workflows/deploy.yml
git commit -m "ci: add GitHub Actions deploy workflow"
git push origin master

Push 完成后,到 GitHub 仓库的 Actions 页面就能看到构建任务在跑。绿色勾表示部署成功,访问 https://jeromexiong.github.io 即可看到最新内容。

效果

之后的工作流就是纯粹的:

1
2
3
4
git add .
git commit -m "新文章"
git push origin master
# 剩下的交给 Actions

不用本地装 Node、不用记住 hexo g -d、不依赖任何本地环境。换电脑、重装系统都不影响发布。