showdown.js的markdown语法高亮问题

我在制作个人博客,使用ajax获取markdown文件,使用showdown.js来解析markdown语法。目前进行得比较顺利,但是有一个问题,我一直没有找到我满意的语法高亮解决方案。

我尝试使用过showdown-highlight来实现语法高亮,效果也比较让人满意,只是在webpack打包的时候出现了这样的报错:

ERROR in bundle.js from UglifyJs
SyntaxError: Unexpected token punc «(», expected punc «:» [./~/showdown-highlight/lib/index.js:20,0]

这个比较尴尬,毕竟代码肯定是要压缩的,否则2MB的js文件加载起来实在太慢了。我尝试查阅了highlight.js的文档,没有相关的信息。

我翻阅了showdown的相关issue,看到有提供这样的解决方案:

https://img2.mukewang.com/5be3a85c0001bc0705830437.jpg

我之前在webpack里引用是这样的:

var showdown = require('showdown'),
    showdownhighlight = require('showdown-highlight');    
var converter = new showdown.Converter({extensions: [showdownhighlight]});

这种引用方式和issue里的解决方案有所不同,琢磨半天也没琢磨透,请问有什么更好的解决方案吗?


Cats萌萌
浏览 1170回答 1
1回答

料青山看我应如是

var converter = new showdown.Converter({extensions: function() {&nbsp; function htmlunencode(text) {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; text&nbsp; &nbsp; &nbsp; &nbsp; .replace(/&amp;/g, '&')&nbsp; &nbsp; &nbsp; &nbsp; .replace(/&lt;/g, '<')&nbsp; &nbsp; &nbsp; &nbsp; .replace(/&gt;/g, '>')&nbsp; &nbsp; &nbsp; );&nbsp; }&nbsp; return [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; type: 'output',&nbsp; &nbsp; &nbsp; filter: function (text, converter, options) {&nbsp; &nbsp; &nbsp; &nbsp; // use new shodown's regexp engine to conditionally parse codeblocks&nbsp; &nbsp; &nbsp; &nbsp; var left&nbsp; = '<pre><code\\b[^>]*>',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right = '</code></pre>',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flags = 'g',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; replacement = function (wholeMatch, match, left, right) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // unescape match to prevent double escaping&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; match = htmlunencode(match);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return left + hljs.highlightAuto(match).value + right;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; return showdown.helper.replaceRecursiveRegExp(text, replacement, left, right, flags);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; ];}()});比较粗暴地把后面的匿名函数当成参数传入,就可以实现了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript