让Hexo博客支持流程图

本文讲的是hexo的插件hexo-filter-mermaid-diagrams

hexo-filter-mermaid-diagrams

1. 快速使用

  1. 安装

    在博客的根目录下使用命令
1
2
3
$ yarn add hexo-filter-mermaid-diagrams
或者
$ npm install hexo-filter-mermaid-diagrams
  1. 配置

    配置hexo的配置文件_config.yml
1
2
3
4
5
6
# mermaid chart
mermaid: ## mermaid url https://github.com/knsv/mermaid
enable: true # default true
version: "7.1.2" # default v7.1.2
options: # find more api options from https://github.com/knsv/mermaid/blob/master/src/mermaidAPI.js
#startOnload: true // default true
  1. 在模版文件引入mermaid.js
    /themes/里找到自己正在使用的主题的文件夹 ,打开里面的layout文件夹,在里面找到一个在文章页面有被加载的模版文件(官方写的是after_footer文件,我的主题没有)根据下面情况引入相应内容。
  • 我的主题使用的是fluid就添加下面的代码到/themes/fluid/layout/plugins/footer.ERB, 如果是其他尾缀类型的模版例如pugswig请去看官方文档
1
2
3
4
5
6
7
8
<% if (theme.mermaid.enable) { %>
<script src='https://unpkg.com/mermaid@<%= theme.mermaid.version %>/dist/mermaid.min.js'></script>
<script>
if (window.mermaid) {
mermaid.initialize({theme: 'forest'});
}
</script>
<% } %>

添加完成后,回到博客根目录的_config.yml,把external_link的值改为false,默认的为true

2. 出现问题

  1. 没有效果

    *记得hexo clean

    原因:语法不一样,三个点后面填写mermaid
1
2
3
` ` `mermaid
内容
` ` `
  1. 报错Error: <svg> attribute viewBox: Expected number, “0 0 -Infinity -Infin…”.
    原因:主题的代码高亮样式冲突了。(主题版本为v1.7.4)
    将主题的代码高亮关了就好了.
1
2
highlight: # 代码高亮
enable: false

优化

在模版footer文件引入mermaid.js的话会在博客的每个页面都加载这个文件,而我们往往并不是每个页面都会有用到这个插件。

  1. 配置部分放到主题配置(/themes/fluid/_config.yml)里
1
2
3
mermaid: # 流程图
enable: true
specific: true # 开启后,只有在文章 Front-matter 里指定 `mermaid: true` 才会在文章页启动公式转换,以便在页面不包含公式时提高加载速度

(就快速使用的第二步里的内容多了specific来控制是否启动转换)
*如果不想放在主题配置里把第二步的theme.post改成config就好了
2. 在/themes/fluid/layout/_partial/plugins新建mermaid.ERB文件,内容如下

1
2
3
4
5
6
7
8
<% if(theme.post.mermaid.enable && (!theme.post.mermaid.specific || (theme.post.mermaid.specific && page.mermaid))) { %>
<%- js_ex(theme.static_prefix.mermaid, "mermaid.min.js") %>
<script>
if (window.mermaid) {
mermaid.initialize({ theme: 'default' });
}
</script>
<% } %>
  1. 引入文件到scripts.ERB

    /themes/fluid/layout/_partial/scripts.ERB最下面添加
1
<%- partial('_partial/plugins/mermaid.ERB') %>
  1. 最后在_static_prefix.yml添加cdn即可
    /themes/fluid/source/_static_prefix.yml最下面添加
1
mermaid: https://cdn.bootcss.com/mermaid/8.4.8/

*此处写死了版本号,想移到配置文件中请自行修改

总结

优化部分的代码还是蛮好懂的,照着本身自带的math进行修改即可。就是代码高亮部分导致的报错并无法显示耗费了许多时间。下次遇到问题先在github的Issues里看看。


本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!