使用 GitHub Actions 自动部署 Hexo 博客

前言

Hexo 是一个快速、简洁且高效的静态博客框架,适合技术类博客搭建。通过 GitHub Actions,我们可以实现代码提交后自动构建并部署博客,彻底告别手动部署,提升效率。


一、创建 GitHub 仓库

登录 GitHub,点击右上角的 +,选择 New repository

新建仓库

填写内容如下:

  • Repository name:自定义你的仓库名,例如 hexo
  • Visibility:选择 Private(私有)
  • 其他选项保持默认,点击 Create repository

仓库信息


二、初始化 Hexo 项目

打开命令行工具(CMD、终端或 PowerShell),执行以下命令:

1
2
3
4
5
6
7
8
# 全局安装 Hexo CLI 工具
npm install hexo-cli -g

# 在当前目录下初始化 Hexo 项目,创建 blog 文件夹
hexo init blog

# 进入 blog 项目目录
cd blog

💡 如果你是 macOS 用户,也可以使用 Homebrew 安装 Hexo:

1
2
3
4
5
6
7
8
# 使用Homebrew安装Hexo 
brew install hexo

# 在当前目录下初始化 Hexo 项目,创建 blog 文件夹
hexo init blog

# 进入 blog 项目目录
cd blog

初始化成功后,blog 文件夹结构如下:

blog结构


三、配置 GitHub Token(权限)

登录 GitHub,依次进入:

SettingsDeveloper SettingsPersonal access tokensTokens (classic),点击 Generate new token (classic)

创建 token

配置如下:

  • Note:如 hexo-blog-token
  • Expiration:选择 No expiration
  • Scopes:勾选 repoworkflow

repo:访问和推送仓库权限
workflow:触发 GitHub Actions 工作流权限

token 权限

生成后复制该 Token。

回到你的 Hexo 源码仓库,打开:
SettingsSecrets and variablesActions
点击 New repository secret

  • NamePERSONAL_TOKEN
  • Secret:粘贴你刚复制的 Token

New secret


四、配置 GitHub Actions 自动部署

blog 目录下创建部署配置文件:

1
.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
34
35
36
37
38
39
40
41
42
43
44
45
# GitHub Actions 配置文件:用于自动部署 Hexo 博客
name: Deploy Hexo

# 当 main 分支被 push 时触发部署流程
on:
push:
branches:
- main

jobs:
deploy:
# 使用最新版 Ubuntu 运行环境
runs-on: ubuntu-latest

# 允许对仓库内容进行写操作(git push)
permissions:
contents: write

steps:
# Step 1:检出仓库源码
- uses: actions/checkout@v4

# Step 2:设置 Node.js 环境
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 18

# Step 3:安装依赖
- name: Install dependencies
run: npm install

# Step 4:生成 Hexo 静态文件
- name: Generate Hexo static files
run: npx hexo generate

# Step 5:部署到 gh-pages 分支
- name: Deploy to gh-pages
uses: peaceiris/actions-gh-pages@v3
with:
personal_token: ${{ secrets.PERSONAL_TOKEN }}
publish_branch: gh-pages
publish_dir: ./public
user_name: 用户名
user_email: 邮箱

五、提交 Hexo 项目到 GitHub

执行以下命令将 Hexo 源码推送到 GitHub:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 确保你在 blog 项目根目录
cd blog

# 初始化 Git 仓库
git init

# 添加全部文件
git add .

# 创建首次提交
git commit -m "首次提交 Hexo 博客源码"

# 将默认分支改为 main
git branch -M main

# 添加远程仓库地址(替换为你自己的仓库地址)
git remote add origin https://github.com/yubanwo/test.git

# 推送到 GitHub
git push -u origin main

成功后,刷新 GitHub 仓库页面,你将看到所有 Hexo 源码已经上传。

上传成功


六、结语

等待 GitHub Actions 执行完成之后,查看 gh-pages 分支发现已经生成文件了:

gh-pages 分支

未来每次更新博客,只需执行:

1
2
3
git add .
git commit -m "更新博客内容"
git push

GitHub Actions 将自动重新构建并部署,无需你手动操作!

此外,你也可以通过 FTP、SFTP、WebDAV 等方式部署到服务器,实现自动上传。


⚠️ 免责声明:本文仅供个人学习与技术研究使用。