一、需求背景
在uniapp+vue3+vite环境中渲染latex数学公式、markdown、代码渲染等等。
二、解决方法
经过一番寻找和使用测试,发现最好用的第三方组件就是:github.com/sbfkcel/tow…
本文主要介绍通过配置第三方组件towxml来实现markdown、latex数学公式、流程图的渲染。
三、配置步骤
-
克隆项目到本地 -
git clone https://github.com/sbfkcel/towxml.git -
安装构建依赖 -
npm install或yarn -
编辑配置文件
towxml/config.js- 根据自行要求,仅保留你需要的功能即可(配置中有详细注释) -
运行
npm run build或yarn run build即可新构建出来的文件在
dist目录下,将dist目录复制到你的小程序项目中并将目录名称改为towxml即可。本文复制到wxcomponents目录,最好跟本文保持一致。 -
编辑/wxcomponents/towxml/decode.json 文件,将路径改为相对路径。
{ "component": true, "usingComponents": { "decode": "./decode", "latex": "./latex/latex", "table": "./table/table", "todogroup": "./todogroup/todogroup", "yuml": "./yuml/yuml", "img": "./img/img" } } -
配置latex数学公式和yum流程图解析引擎
- 服务器需要安装
nodejs 8.0+ - 克隆markdown-server项目
git clone https://github.com/sbfkcel/markdown-server - 安装依赖
npm i - 运行服务
node index.js - 访问服务
http://127.0.0.1:8001?tex=hello- 如果有显示Hello字眼则说明服务部署成功
- 端口号可打开index.js文件自行修改(文件最后一行)
- 将服务地址
http://服务器IP:8001?tex、http://服务器IP:8001?yuml填写到towxml/config.js中// 数学公式解析API latex:{ api:'http://127.0.0.1:8001/latex/?tex' }, // yuml图解析APPI yuml:{ api:'http://127.0.0.1:8001/yuml/?yuml' }, ```
- uniapp环境的话需要将towxml/index.js函数导出方式改以下
export const useTowxml = (str,type,option)=>{ option = option || {}; let result; switch (type) { case 'markdown': result = parse(md(str),option); break; case 'html': result = parse(str,option); break; default: throw new Error('Invalid type, only markdown and html are supported'); break; }; return result; }; - 引用towxml组件
{ "path": "detail/detail", "style": { "usingComponents": { "towxml": "/wxcomponents/towxml/towxml" } } } - 在页面中使用
- 导入组件
import {useTowxml} from '@/wxcomponents/towxml/index.js'; - 封装函数
const useMarkdown = (value: string) => useTowxml(value || '', 'markdown') - 在模板中使用
<towxml :nodes="useMarkdown(currentQuestion.analysis)"/>
- 重新编译即可,若不生效,请清除缓存重新打开微信开发者工具。
总结
本文主要介绍了微信小程序中使用towxml库来支持渲染markdown内容。
渲染latex和yuml时需要引用第三方引擎markdown-server解析,需要在towxml中配置好解析地址。
该引擎支持docker部署。