部署Hexo博客到GitHub Pages

目标:

  1. 博客源代码放到Github私有仓库上;

  2. 直接往源代码私有仓上传或者直接在Github后台编辑Markdown文档,就能自动执行更新到Github Pages,方便多端工作或者在外没有本地Node.js的环境下也能更新博客;

  3. GitHub Pages仓库不需要保留每次更新的commit记录,没什么意义,上到Github看会很难受,万一不小心发了秘钥之类的信息也能及时删除。

步骤

  1. 创建Hexo博客
    此步骤参考Hexo官网,不再赘述。

  2. 创建用来部署到Github Pages的SSH的秘钥

    1
    ssh-keygen -C "your@mail.com" -f ~/.ssh/github-actions-deploy-key
  3. 将公钥 ~/.ssh/github-actions-deploy-key.pub 配置到GitHub Pages所在仓库的Deploy keys中,配置位置在
    GitHub -> Repo -> Settings -> Deploy keys -> Add deploy key
    注意需要给写入权限。

  4. 将私钥 ~/.ssh/github-actions-deploy-key 配置到博客源代码所在仓库的Actions secrets and variables中,配置位置在
    GitHub -> Repo -> Settings -> Secrets and variables -> Actions -> New repository secret
    创建 Name 为 TARGET_REPO_SSH_KEY 的配置,将私钥内容粘贴进去。

  5. 在Hexo博客代码根目录下,创建 .github/workflows/deploy.yml 文件,用来配置使用GitHub Actions触发自动构建,示例配置文件内容如下:

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
51
52
53
54
name: Build and Deploy to Github Pages

on:
push:
branches:
- master # 触发工作流的分支

jobs:
build-and-deploy:
runs-on: ubuntu-latest

steps:
# 检出代码
- name: Checkout source repository
uses: actions/checkout@v3

# 设置 Node.js 环境
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 18 # 根据你的项目需求选择合适的 Node.js 版本

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

# 构建项目
- name: Build project
run: npm run build

# 配置自定义域名
- name: Set up custom domain
run: echo "your.domain" > public/CNAME

# 配置 SSH
- name: Set up SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.TARGET_REPO_SSH_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts

# 将构建结果推送到外部仓库
- name: Deploy to external repository
run: |
git config --global user.name "Your Name"
git config --global user.email "your@mail.com"
cd public
git init
git checkout -b gh-pages
git add .
git commit -m "Deploy via GitHub Actions"
git remote add origin git@github.com:username/username.github.io.git
git push -u origin gh-pages --force
  1. 结束,这个时候你提交Markdown文档到仓库就会自动构建并发布到GitHub Pages了。

评论