小程序mp-html高亮代码块的md语法显示

1,513 阅读1分钟

最近在优化小程序的样式,发现之前使用的mp-html组件的代码部分有高亮,部分没有,查看问题是显示的地方没有准确识别代码块是html还是js,看起来很难看,查看相关的插件的github以及文档。

4060fb42da4f7fbc5f4204d4953c835.jpg

总结一下
第一种方案:可以npm install mp-html,修改tools的config.js文件,将其需要的功能去掉注释

image.png

然后按照自己需要的打包,文档的具体地址:jin-yufeng.gitee.io/mp-html/#/

image.png

第二种方案就是扫描二维码,观看视频后生成zip包,比较简单

957acd23115bb385506612d7418593c.jpg

然后将其放到components,组件导入使用,这里选择自己的代码块语言即可代码块高亮

<mp-html :tag-style="tag_style" :content="item.content" :container-style="container_style" selectable="true" class='richText' />

import mpHtml from '@/components/mp-html/components/mp-html/mp-html.vue';
import {marked} from 'marked'

data(){
    return {
        tag_style: {
            h1: 'line-height: 50px;font-size:16px;',
            h2: 'line-height: 50px;font-size:16px',
            h3: 'line-height: 50px;font-size:16px',
            h4: 'line-height: 50px;font-size:16px',
	},
	container_style: 'font-size:15px;overflow-x: hidden;',
    }
}

methods:{
    getContent(){//正则表达式替换形成html标签
        this.item.content = marked(this.item.content)
	.replace(/<h1([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<h1')
	.replace(/<h1([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<h1')
	.replace(/<h1>/ig, '<h1 class="h1">')
        .replace(/<h2([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<h2')
	.replace(/<h2([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<h2')
	.replace(/<h2>/ig, '<h2 class="h2">')
        .replace(/<h3([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<h3')
	.replace(/<h3([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<h3')
	.replace(/<h3>/ig, '<h3 class="h3">')
        .replace(/<h4([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<h4')
        .replace(/<h4([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<h4')
	.replace(/<h4>/ig, '<h4 class="h4">')
        .replace(/<h5([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<h5')
	.replace(/<h5([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<h5')
	.replace(/<h5>/ig, '<h5 class="h4">')
        .replace(/<h6([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<h6')
	.replace(/<h6([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<h6')
	.replace(/<h6>/ig, '<h6 class="h6">')
        .replace(/<code([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<code')
	.replace(/<code([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<code')
	.replace(/<code>/ig, '<code class="language-javascript">')
    }
}