本文描述的过程主要为如何在本地部署Hexo。在了解和熟悉本地部署的流程之后,更推荐利用 GitHub Actions 实现自动化部署 Hexo 到 Github Pages

前置条件

安装下列软件:

  • Node.js
  • Git

安装

安装 hexo:

1
npm install -g hexo-cli

查看版本:

1
hexo v

创建

创建 blog 文件夹

1
2
3
4
mkdir blog
cd blog

hexo init

部署 hexo

1
hexo g

本地化预览

1
hexo s

写作

创建草稿

1
hexo new draft hello-hexo # hello-hexo 为文件名

发布

1
hexo publish hello-hexo # hello-hexo 为文件名

图片

全局资源文件夹

如果你的Hexo项目中只有少量图片,那最简单的方法就是将它们放在 source/images 文件夹中。 然后通过类似于 ![](/images/image.jpg) 的方法访问它们。

文章资源文件夹

config.yml 文件中的 post_asset_folder 选项设为 true

1
post_asset_folder: true

在通过 hexo new [layout] <title> 命令创建新文章时,会自动创建一个与文章同名的文件夹。将所有与该文章有关的资源放在这个关联文件夹中之后,可以通过相对路径来引用它们。

相对路径引用的标签插件

当打开文章资源文件夹功能后,把一个 example.jpg 图片放在资源文件夹中,如果通过使用相对路径的常规 markdown 语法 ![](example.jpg) ,它将不会出现在首页上。

正确的引用图片方式是使用下列的标签插件 :

1
2
{% asset_img example.jpg This is an example image %}
{% asset_img "spaced asset.jpg" "spaced title" %}

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: Deploy Hexo to GitHub Pages

on:
push:
branches:
- main # 或你使用的默认分支名称

jobs:
deploy:
runs-on: ubuntu-22.04

steps:
- name: Checkout blog source
uses: actions/checkout@v4
with:
path: blog

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "22" # 设置 Node.js 版本

- name: Cache dependencies
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-

- name: Install dependencies
run: npm install
working-directory: ./blog

- name: Install Hexo CLI
run: npm install -g hexo-cli
working-directory: ./blog

- name: Install Hexo Theme
run: npm install hexo-theme-stellar
working-directory: ./blog

- name: Generate static pages
run: hexo generate
working-directory: ./blog

- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v4
with:
personal_token: ${{ secrets.PERSONAL_TOKEN }}
publish_dir: ./blog/public
external_repository: username/username.github.io # 更改为你的 GitHub Pages 仓库, username 是你的用户名
publish_branch: main # GitHub Pages 分支