用Hexo和NexT构建博客

文档参考

安装 Hexo 和 NexT

1
2
3
npm install hexo-cli -g
hexo init
git clone https://github.com/theme-next/hexo-theme-next themes/next

配置 Hexo

参考Hexo Configuration

  • 修改项目根目录下的_config.yml文件
  • 网站信息主要修改 title, subtitle, description, author, timezone, url这几项,其余的稍后修改
  • language: zh-CN的支持是由NexT提供的,默认是没有效果的
  • theme: next其中next取决于你安装在theme下的目录名

配置 NexT

参考NexT Configuration

  1. theme/next目录下复制一份_config.ymlsource/data/next.yml(具体路径取决于你的_config.yml)
  2. 修改next.yml中需要的配置项: 美化相关参考Theme Settings, 第三方服务相关参考Third Party Services
  • 个人建议启用第三方服务中的Math Equations支持以方便书写数学表达式

测试和部署

参考NexT Deployment

本地测试

  • 构建前需要确保至少有一篇Post,否则可能会出现404的情况
1
hexo clean && hexo generate && hexo server --debug

手动部署

  • 在配置文件 _config.yml 的最后加入以下行

    1
    2
    3
    4
    deploy:
    type: git
    repo: # Git仓库路径
    branch: master
  • Git部署需要先安装对应的插件npm install hexo-deployer-git,然后和测试时类似

1
hexo clean && hexo generate && hexo deploy

持续集成

参考Github Action Documentation

  • 页面源代码会被公开

  • 本方法实现的持续集成实际上就是让代码托管帮我们执行上述 手动部署 的过程, 因此需要先配置手动部署的文件

  • 仓库下需要有两个 branch 。其中 master 分支是放生成后的静态页面, 另一个分支(source)放你的源码

  • source 分支根目录下创建 .github/workflows/nodejs.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
    name: Hexo Auto Deploy
    on:
    push:
    branches: [ source ]
    jobs:
    build:
    runs-on: ubuntu-latest
    strategy:
    matrix:
    node-version: [12.x]
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
    uses: actions/setup-node@v1
    with:
    node-version: ${{ matrix.node-version }}
    - run: npm ci
    - name: Build and Deploy
    uses: SeaLoong/hexo-deploy-action@master
    env:
    PERSONAL_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    PUBLISH_REPOSITORY: ${{ github.repository }}
    BRANCH: master
    PUBLISH_DIR: ./public
  • 然后把文件提交到Github仓库即可

使用博客

在上面进行配置的过程中应当已经学会简单使用Hexo了,下面算是一些总结的部分

新建Post

hexo new <title>hexo new post <title>会创建文件于source/_post/<title>.md,其中最开始的内容应当类似如下

1
2
3
4
5
---
title: Hexo+NexT构建博客
date: 2020-04-11 03:23:32
tags: [Hexo, NexT]
---

此外,如果有相关配置的话,可以增加categories,comments等项以设置对应配置的属性

然后写下你要写的内容

提交Post

如果是手动部署就直接执行对应的命令行

如果是持续集成一般只要提交commit即可

  • 在提交之前可以先进行本地测试来预览一下

几个坑

  • 没有Post的时候访问根页面时404
  • 生成Post时出现
1
2
ERROR Render HTML failed: xxx/index.html
TypeError: Cannot read property 'replace' of null

参考https://github.com/hexojs/hexo/issues/3859

还有可能是在配置文件中把一些功能打开但是没用安装对应的依赖导致的(其他报错也可能是这个原因)