代码高亮

最后更新于:2019-12-17

想要实现小程序的代码高亮,可以参考这一篇《基于 wxParse 实现 WordPress 版小程序代码高亮》。

第一步:需要下载修改版 wxParse ,解压替换掉小程序源码包里的 wxParse 目录。

第二步:需要对内容进行转换解析。搜索:WxParse.wxParse('article', 'html', res.content.rendered, this,5),更改为:

let contents = res.content.rendered.replace(/<pre[^>]*><code class=\"([^\s]*)\">/g,"<pre class=\"pure-highlightjs $1\">").replace(/<\/code><\/pre>/g,"</pre>")WxParse.wxParse('article', 'html', contents, this,5)

第三步:需要引用代码高亮样式。打开 detail.wxss 引用样式 @import"../../wxParse/prism.wxss";

第四步:添加内容时,需要使用高亮代码:

<pre class="pure-highlightjs"><code class="高亮语言,比如php,javascript等">高亮代码部分...</code></pre>

完成以上步骤,就可以实现小程序内容代码高亮。

丸子小程序资讯版已经提供了代码高亮版本,但是考虑到大部分小程序都不需要代码高亮功能,因此,默认是未启用代码高亮,如果需要启用微信小程序资讯版代码高亮,方法如下:

1、修改 html2json.js 文件,把 //var highlight = require(‘./highlight.js’); 斜杠注释删掉

2、修改 detail.wxss 文件,引入代码高亮样式 @import “../../wxParse/prism.wxss”;

3、修改 mixins.js 文件,把 WxParse.wxParse('article', 'html', res.content.rendered, this,5)更改如下:

let contents = res.content.rendered.replace(/<pre[^>]*><code class=\"([^\s]*)\">/g,"<pre class=\"pure-highlightjs $1\">").replace(/<\/code><\/pre>/g,"</pre>")WxParse.wxParse('article', 'html', contents, this,5)