使用单仓库部署的好处

  • 无需另设私人仓库储存源码
  • 无需另外生成token

新建仓库

新建一个名为[username].github.io的公共仓库用于存放博客源码和构建后的页面

配置Github Actions

来到仓库的Settings-Actions-General-Workflow permissions,选择Read and write permissionsAllow GitHub Actions to create and approve pull requests,以确保Github Actions有读写权限

.github 文件夹下添加 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
61
name: 自动部署
on:
push:
branches:
- code # 存放源代码的分支名
release:
types:
- published

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 检查分支
uses: actions/checkout@v4
with:
ref: code # 存放源代码的分支名
fetch-depth: 0
- name: Sync local file timestamps
run: |
git ls-files -z | while read -d '' path; do touch -d $(git log -1 --format="@%ct" "$path") "$path"; done

- name: 安装 Node
uses: actions/setup-node@v4
with:
node-version: "20"

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

- name: 缓存 Hexo
id: cache-npm
uses: actions/cache@v4
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 --save

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

- name: 部署到Github
uses: JamesIves/github-pages-deploy-action@v4
with:
branch: main # 存放构建后页面的分支名
folder: public
commit-message: "${{ github.event.head_commit.message }}"

本地仓库连接到Github

添加屏蔽项

打开.gitignore,将主题下的.git文件夹加入屏蔽项

1
2
3
4
5
6
7
8
9
.DS_Store
Thumbs.db
db.json
*.log
node_modules/
public/
.deploy*/
.deploy_git*/
themes/[theme]/.git # [theme]为你所用的主题名

为了保证能顺利推送主题文件夹,建议先将主题下的.git文件夹移走

连接仓库并推送源码

打开Git Bash,依次输入:

1
2
3
4
5
6
git init
git remote add origin git@github.com:[username]/[username].github.io.git
git checkout -b code # 注意这里为存放源码的分支,需要与`autodeploy.yml`中一致
git add .
git commit -m "blog update"
git push origin code # 推送到存放源码的分支

等待Github Actions完成后,查看主题文件夹是否成功推送到Github的源码分支,成功后即可将.git文件夹移回

Github Pages配置

在仓库的Settings-General-Default branch,更改默认分支为构建后页面的分支

来到Settings-Pages-Build and deployment-Branch,设置为构建后页面的分支

等待部署完成后即可正常访问Github Page