Hexo 配置备忘录

修复 \(\KaTeX\) 支持,自动格式化

修复 KaTeX 支持

因为 NexT 对 \(\KaTeX\) 的支持疏于维护,而 MathJax 又是出了名的慢,所以需要进行手动修复以启用 \(\KaTeX\)

首先,禁用所有与数学公式支持有关的配置项 (尤其不要启用 MathJax)

NexT config file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Math Formulas Render Support
# Warning: Please install / uninstall the relevant renderer according to the documentation.
# See: https://theme-next.js.org/docs/third-party-services/math-equations
# Server-side plugin: https://github.com/next-theme/hexo-filter-mathjax
math:
# Default (false) will load mathjax / katex script on demand.
# That is it only render those page which has `mathjax: true` in front-matter.
# If you set it to true, it will load mathjax / katex script EVERY PAGE.
every_page: false

mathjax:
enable: false
# Available values: none | ams | all
tags: all

katex:
enable: false
# See: https://github.com/KaTeX/KaTeX/tree/master/contrib/copy-tex
copy_tex: false

然后修改 NexT 设置如下

NexT config file
1
2
3
4
# Define custom file paths.
# Create your custom files in site directory `source/_data` and uncomment needed files below.
custom_file_path:
head: source/_data/head.njk

source/_data/head.njk 中将 Browser · KaTeX 中加载脚本的三行代码复制进去即可

自动格式化

使用 Prettier 对 Markdown 文档进行格式化,并通过 Git Hooks 实现每次 commit 均会自动格式化一次

如果嫌 commit 时间过长也可以借助 GitHub Action 实现自动格式化并 commit, 这里只列出基于 Git Hooks 的配置步骤

安装 Husky (repo) 和 Prettier (repo)

1
2
npm install husky --save-dev
npm install prettier --save-dev

然后执行

1
2
3
4
npm set-script prepare "husky install"
npm set-script formatting "prettier --write source/"
npm run prepare
npx husky add .husky/pre-commit "npm run formatting"

之后每次 commit 都会格式化 source 中的文件了

优化

按照上述方式配置之后,每次 commit 都会全局格式化,这显然不是什么好设计,所以可以按 Prettier 文档 修改 .husky/pre-commit, 使得 Prettier 每次只会自动格式化修改的文件

.husky/pre-commit
1
2
3
4
5
6
7
8
9
10
11
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0

echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write

echo "$FILES" | xargs git add

exit 0

之后再执行

1
npx husky add .husky/post-commit "git update-index -g"

即可