MOFASHY

Live Is Life

基于 hexo 框架的个人博客搭建

Hexo 是一个快速、简洁且高效的博客框架,配合 GitHub Pages,可以方便、快捷的创建个人博客。

提前准备

使用 hexo 搭建博客之前需要准备的工具:

安装 hexo

安装 hexo ,在终端中输入命令:

1
npm install hexo-cli -g

新建一个专门用于存放 hexo 博客文件的目录(如:hexo),然后在这个目录下右键通过终端打开,接下来初始化hexo,命令如下:

1
2
3
4
5
6
7
8
9
# 进入 hexo 目录
cd hexo
# hexo init 博客名(英文)
hexo init blog
cd blog
# 安装依赖
npm install
# 启动服务预览博客
hexo server

创建完成后,指定目录下生成的关键文件目录结构如下:

1
2
3
4
5
6
7
8
.
├─...
├─node_modules: # node 存放依赖包
├─public: # 存放 hexo 生成的网页文件
├─scaffolds: # 脚手架目录,存放生成文章的模板
├─source: # 存放 MARKDOWN 文章
├─themes: # 存放主题
└─_config.yml: # 配置文件

配置第三方主题

hexo 拥有非常丰富的第三方主题,可以根据个人喜好挑选。除了可以从官网罗列的四百多款主题中挑选,还可以在 GitHub 上搜索未在官网上罗列的主题。博主比较喜欢简洁的主题,所以用的是一款偏小众的主题—— Hacker,命令如下:

1
2
3
4
5
6
# 进入 themes 目录
cd themes
# 使用 git 克隆主题
git clone https://github.com/CodeDaraW/Hacker.git hacker
# 删除 git 信息,否则后续会被当成子模块添加到 git
rm -rf .git

编辑_config.yml文件,把 hexo 默认主题改成上面下载好的主题:

1
2
- theme: landscape
+ theme: hacker

部署到 GitHub Pages

为了更好的管理 hexo 源文件和生成的静态网页文件,需要用到两个仓库,然后通过 GitHub Actions 上传整个博客源文件到私有仓库(下面用blog_repo代替)并自动部署到 GitHub Pages 所在的公开仓库(下面用username.github.io代替)。

配置 SSH Deploy Key

为了跨仓库部署,需要用到 SSH deploy key 或者 personal access token(这里用 deploy key演示)。

1
ssh-keygen -t rsa -m pem -b 4096 -C "youremailhere@example.com" -N ""

在公开库username.github.io中前往Settings > Deploy keys,将公钥内容贴到 Deploy keys 里。

在私有库blog_repo中前往Settings > Secrets and variables > Actions > Secrets,将私钥内容贴到 Repository secrets 里。

配置 Actions

查看你电脑上的 Node.js 版本并记下(如:22.x.y):

1
node --version

在私有库blog_repo中前往 Settings > Pages > Source 。 将 source 更改为 GitHub Actions,然后保存。

在私有库blog_repo中建立.github/workflows/pages.yml,并填入以下内容 (将 22 替换为上个步骤中记下的版本):

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
name: Pages

on:
push:
branches:
- main # default branch

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Use Node.js 22
uses: actions/setup-node@v4
with:
node-version: "22" # 填写对应的 node 版本
- name: Cache NPM dependencies
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.OS }}-npm-cache
restore-keys: |
${{ runner.OS }}-npm-cache
- name: Install Dependencies
run: npm install
- name: Build
run: npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v4
with:
deploy_key: ${{ secrets.DEPLOY_KEY }}
external_repository: username/external-repository # /username/username.github.io
publish_branch: your-branch # 默认: gh-pages
publish_dir: ./public
commit_message: ${{ github.event.head_commit.message }}

推送 blog_repo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cd blog
# 初始化 git
git init
# 查看本地分支
git branch
# GitHub 最新默认主分支改成了 main
# 如果本地分支不是 main,需要重命名为 main
git branch -m master main
# 添加远程仓库地址(私有仓库 blog_repo)
git remote add origin <blog_repo_url>
# 同步远程仓库
git pull origin main --allow-unrelated-histories
# 推送到远程仓库,成功后会自动触发 Actions
git push -u origin main

部署完成后,前往 username.github.io 查看网页。