一般寫博客都採用md格式,快捷方便,但是寫好之後爲了方便查看,我們需要將md格式的代碼解析。
markdown-it
本示例中採用的是markdown-it來解析md格式的代碼。
highlight.js
本示例中採用的是highlight.js來進行代碼高亮顯示。
但是highlight.js不支持行號,這會導致代碼看起來不方便,本示例結合給博客的highlight.js添加行號和行號高亮中的方法來給代碼添加行號。
const MarkdownIt = require('markdown-it')
const hljs = require('highlight.js')
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
// 此處判斷是否有添加代碼語言
if (lang && hljs.getLanguage(lang)) {
try {
// 得到經過highlight.js之後的html代碼
const preCode = hljs.highlight(lang, str, true).value
// 以換行進行分割
const lines = preCode.split(/\n/).slice(0, -1)
// 添加自定義行號
let html = lines.map((item, index) => {
return '<li><span class="line-num" data-line="' + (index + 1) + '"></span>' + item + '</li>'
}).join('')
html = '<ol>' + html + '</ol>'
// 添加代碼語言
if (lines.length) {
html += '<b class="name">' + lang + '</b>'
}
return '<pre class="hljs"><code>' +
html +
'</code></pre>'
} catch (__) {}
}
// 未添加代碼語言,此處與上面同理
const preCode = md.utils.escapeHtml(str)
const lines = preCode.split(/\n/).slice(0, -1)
let html = lines.map((item, index) => {
return '<li><span class="line-num" data-line="' + (index + 1) + '"></span>' + item + '</li>'
}).join('')
html = '<ol>' + html + '</ol>'
return '<pre class="hljs"><code>' +
html +
'</code></pre>'
}
})
// req.body.content 代表md代碼
let articleContentHtml = md.render(`@[toc]${req.body.content}`)
在vue中的渲染
<template>
<!-- 渲染生成的html代碼 -->
<div class="article-content" v-html="info.articleContentHtml"></div>
</template>
<script>
// 引入默認樣式
import 'highlight.js/scss/default.scss'
// 引入個性化的vs2015樣式
import 'highlight.js/styles/vs2015.css'
</script>
<style lang="scss">
// 添加行號樣式
pre.hljs {
padding: 8px 2px;
border-radius: 5px;
position: relative;
ol {
list-style: decimal;
margin: 0;
margin-left: 40px;
padding: 0;
li {
list-style: decimal-leading-zero;
position: relative;
padding-left: 10px;
.line-num {
position: absolute;
left: -40px;
top: 0;
width: 40px;
height: 100%;
border-right: 1px solid rgba(0, 0, 0, .66);
}
}
}
b.name {
position: absolute;
top: 2px;
right: 12px;
z-index: 10;
color: #999;
pointer-events: none;
}
}
</style>
渲染之後的樣式如下:
在代碼中更詳細的使用可查看vue-blog 和 vue-blog-express。