预期目标

在博客仓库写完 Markdown 格式的文章,然后 git 提交推送到 Github,自动在 https://yelexin.github.iohttps://zuweiye.com 完成部署,内容保持一致。

适用于你有自己的服务器站点,同时又想把博客同步到 Github Pages 的情况。

前置条件

  1. 搭建 Hexo 博客项目。

  2. 创建你账号的 Github Pages

  3. 创建一个 Personal Access Token

配置 Github Actions

建议在 Github 上创建一个 Private 仓库,用于存储你的博客源码,因为 Hexo 的配置文件中涉及到 Secret 一类的敏感信息。

给你的 Blog 源码项目创建一个 Github Actions,如图所示:

创建 Github Actions

  • node-version 只保留 12.x,因为高版本的 Node 无法正常使用 Hexo 部分功能。
  • 在 steps 使用下面几条语句:
1
2
3
- run: npm install
- run: npm run build
- run: npm run deploy

完整的 .github/workflows/node.js.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
# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: Node.js CI

on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [12.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm install
- run: npm run build
- run: npm run deploy

配置 Hexo

确保你安装了 hexo-deployer-sftphexo-deployer-git Hexo 插件。

在 Hexo 博客源文件目录下修改 _config.yml

1
2
3
4
5
6
7
8
9
10
11
deploy:
- type: git
repo: https://{你的 Github 用户名}:{Github Personal Access Token}@github.com/{你的 Github 用户名}/{你的 Github 用户名}.github.io.git
token: '{Github Personal Access Token}'
branch: master
- type: sftp
host: 你的服务器 IP host
user: 你的服务器登录用户名
pass: 你的服务器登录密码
remotePath: 博客静态文件在你服务器上的路径
port: SSH 端口号,默认 22

修改 package.json

在 scripts 中加入:

1
2
3
4
"scripts": {
"build": "hexo g",
"deploy": "git config --global user.email \"{你的 Github 邮箱}\" && git config --global user.name \"{你的 Github 用户名}\" && hexo d"
}

提交代码,可以在 Github Actions 中观察 CI / CD 运行情况。