利用 GitHub Actions 自动部署 Hexo 博客

操作步骤

获取 Token

访问 Github->头像(右上角)->Settings->Developer Settings->Personal access tokens->generate new token,创建的 Token 名称随意,但必须勾选 repo 项 和 workflows 项。

创建存放源码的私有仓库

创建完成后,需要把博客的源码 push 到这个仓库里,具体操作就不赘述了,大家可以自行百度

配置 Github Action

在博客根目录下新建 .github 文件夹,然后在 .github 文件夹内新建 workflows 文件夹,再在 workflows 文件夹内新建 autodeploy.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
name: 自动部署
on:
push:
branches:
- master
release:
types:
- published

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 检查分支
uses: actions/checkout@v2
with:
ref: master

- name: 安装 Node
uses: actions/setup-node@v1
with:
node-version: "18.x"

- name: 安装 Hexo
run: |
export TZ='Asia/Shanghai'
npm install hexo-cli -g

- name: 缓存 Hexo
id: cache-npm
uses: actions/cache@v3
env:
cache-name: cache-node-modules
with:
path: node_modules
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-

- name: 安装依赖
if: ${{ steps.cache-npm.outputs.cache-hit != 'true' }}
run: |
npm install gulp-cli -g
npm install --save

- name: 生成静态文件
run: |
hexo clean
hexo generate

- name: 部署到Github
uses: JamesIves/github-pages-deploy-action@v4
with:
         token: # 部署密钥
         repository-name: # 公共仓库名
         branch: master
folder: public
commit-message: "${{ github.event.head_commit.message }} Updated By Github Actions"

之后再运行 git 提交指令,将博客源码提交到 github 上。

1
git add .
1
git commit -m "github action update"
1
git push origin master

版权声明

本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 协议 ,转载请注明出处!


利用 GitHub Actions 自动部署 Hexo 博客
https://www.xukaiyyds.cn/posts/38b3badf/
作者
xukai
发布于
2022年3月18日
更新于
2023年3月31日
许可协议