0%

Hexo添加KaTeX插件

在 Hexo 的 Next 主题中集成 KaTeX 数学公式渲染


1. 更换 Markdown 渲染器

Hexo 默认的渲染器可能不支持 KaTeX,需更换为兼容的渲染器:

1
2
3
npm un hexo-renderer-marked --save  # 卸载默认渲染器
npm i hexo-renderer-markdown-it --save # 安装 markdown-it 渲染器
npm install @traptitech/markdown-it-katex --save # 安装 KaTeX 插件

2. 配置 markdown-it

在 Hexo 根目录的 _config.yml 中添加配置:

1
2
3
4
5
6
markdown:
plugins:
- "@traptitech/markdown-it-katex"
anchors:
level: 2
collisionSuffix: 'v'

3. 修改 Next 主题配置

在 Next 主题的配置文件 (themes/next/_config.yml) 中:

  • 关闭 MathJax(避免冲突):

    1
    2
    3
    math:
    mathjax:
    enable: false
  • 启用 KaTeX

    1
    2
    3
    4
    katex:
    enable: true
    copy_tex: true # 允许复制公式代码
    vendor_css: false # 如果手动加载 CSS 可设为 true

4. 引入 KaTeX 资源

在主题布局文件中添加 KaTeX 的 CSS 和 JS:

  • 编辑 themes/next/layout/_partials/head/head.swig,在 <head> 内添加:

    1
    2
    3
    {% if theme.katex.enable %}
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
    {% endif %}
  • 编辑 themes/next/layout/_partials/footer.njk(或类似文件),在末尾添加:

    1
    2
    3
    4
    5
    6
    {% if theme.katex.enable %}
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"
    onload="renderMathInElement(document.body, { delimiters: [{left: '$$', right: '$$', display: true}, {left: '$', right: '$', display: false}] });">
    </script>
    {% endif %}

5. 文章启用 KaTeX

在文章的 Front-matter 中添加 katex: true

1
2
3
4
5
6
7
8
9
10
---
title: 测试文章
date: 2023-01-01
katex: true
---

行内公式:$E = mc^2$

块级公式:
$$ \sum_{i=1}^n i = \frac{n(n+1)}{2} $$

6. 处理特殊符号转义

若公式中的 _ 被转义,需调整渲染器配置。在 Hexo 的 _config.yml 中:

1
2
3
4
5
6
7
markdown:
html: true # 允许 HTML 标签
xhtmlOut: false
breaks: false
linkify: true
typographer: true
quotes: '“”‘’'

7. 测试与清理缓存

生成并预览效果:

1
hexo clean && hexo generate --debug && hexo server

访问 http://localhost:4000 查看公式是否正确渲染。


常见问题

  • 公式未渲染:检查控制台是否有资源加载错误,确认 CDN 链接有效。
  • 符号错位:确保没有多余的转义字符,使用 \\ 代替 \
  • 主题版本差异:不同 Next 版本配置项可能不同,参考官方文档调整。

完成以上步骤后,即可在 Hexo 博客中使用 KaTeX 渲染数学公式。