关于uniapp:uniappmarkdown渲染解析md转html及代码高亮

8次阅读

共计 1880 个字符,预计需要花费 5 分钟才能阅读完成。

明天给大家分享一个在 uniapp 我的项目中用到的 markdown 语法解析插件 uaMarkdown。

如下图:编译至 H5+ 小程序 +App 端 成果。

应用 markdown-ithighlight.js封装组件。

// 引入 markdown-it 和 highlight.js 插件
import MarkdownIt from '@/plugins/markdown-it.min.js'
import hljs from '@/plugins/highlight/highlight.min.js'
// import '@/plugins/highlight/github-dark.min.css'
import '@/plugins/highlight/atom-one-light.css'
import parseHtml from '@/plugins/html-parser.js'

初始 markdown 组件

const markdown = MarkdownIt({
   html: true,
   highlight: function(str, lang) {
    let preCode = ""
    try {preCode = hljs.highlightAuto(str).value
    } catch (err) {preCode = markdown.utils.escapeHtml(str);
    }
    // 自定义行号
    const lines = preCode.split(/\n/).slice(0, -1)
    let html = lines.map((item, index) => {
      // 去掉空行
      if(item == ''){return ''}
      return '<li><span class="line-num"data-line="' + (index + 1) + '"></span>' + item +'</li>'
    }).join('')
    html = '<ol style="padding: 0px 30px;">' + html + '</ol>'
    
    // 代码复制
    copyCode.push(str)
    let htmlCode = `<div class="markdown-wrap">`
      // #ifndef MP-WEIXIN
        htmlCode += `<div style="color: #aaa;text-align: right;font-size: 12px;padding:8px;">`
          htmlCode += `${lang}<a class="copy-btn" code-data-index="${copyCode.length - 1}" style="margin-left: 8px;"> 复制代码 </a>`
        htmlCode += `</div>`
      // #endif
        htmlCode += `<pre class="hljs" style="padding:0 8px;margin-bottom:5px;overflow: auto;border-radius: 5px;"><code>${html}</code></pre>`;
      htmlCode += '</div>'
    return htmlCode
  }
})

解析 md 语法结构

const parseNodes = (value) => {if(!value) return
   
   let htmlString = ''if (value.split("```").length % 2) {
    let msgContent = value
    if(msgContent[msgContent.length-1] != '\n'){msgContent += '\n'}
    htmlString = markdown.render(msgContent)
  } else {htmlString = markdown.render(msgContent.value)
  }
  
  // #ifndef APP-NVUE
  return htmlString
  // #endif
  
  // nvue 模式下将 htmlString 转成 htmlArray,其余状况 rich-text 外部转
  // 注:本示例我的项目还没应用 nvue 编译
  // #ifdef APP-NVUE
  return parseHtml(htmlString)
  // #endif
}

疾速应用

  • 根底用法
const mdvalue = '### uniapp markdwon'
<ua-markdown :source="mdvalue" />
  • 禁用行号
<ua-markdown :source="xxx" :showLine="false" />

ua-markdown 组件曾经公布插件市场,能够收费下载应用。

https://ext.dcloud.net.cn/plugin?id=13307

正文完
 0