在此系列文章的第一篇,咱们介绍了 Vuepress 如何让 Markdown 支持 Vue 组件的,但没有提到非 Vue 组件的其余部分如何被解析。html
今天,咱们就来看看 Vuepress 是如何利用 markdown-it 来解析 markdown 代码的。vue
markdown-it 是一个辅助解析 markdown 的库,能够完成从 # test
到 <h1>test</h1>
的转换。webpack
它同时支持浏览器环境和 Node 环境,本质上和 babel 相似,不一样之处在于,babel 解析的是 JavaScript。git
说到解析,markdown-it 官方给了一个在线示例,可让咱们直观地获得 markdown 通过解析后的结果。好比仍是拿 # test
举例,会获得以下结果:github
[
{
"type": "heading_open",
"tag": "h1",
"attrs": null,
"map": [
0,
1
],
"nesting": 1,
"level": 0,
"children": null,
"content": "",
"markup": "#",
"info": "",
"meta": null,
"block": true,
"hidden": false
},
{
"type": "inline",
"tag": "",
"attrs": null,
"map": [
0,
1
],
"nesting": 0,
"level": 1,
"children": [
{
"type": "text",
"tag": "",
"attrs": null,
"map": null,
"nesting": 0,
"level": 0,
"children": null,
"content": "test",
"markup": "",
"info": "",
"meta": null,
"block": false,
"hidden": false
}
],
"content": "test",
"markup": "",
"info": "",
"meta": null,
"block": true,
"hidden": false
},
{
"type": "heading_close",
"tag": "h1",
"attrs": null,
"map": null,
"nesting": -1,
"level": 0,
"children": null,
"content": "",
"markup": "#",
"info": "",
"meta": null,
"block": true,
"hidden": false
}
]
复制代码
通过 tokenizes 后,咱们获得了一个 tokens: web
咱们也能够手动执行下面代码获得一样的结果:npm
const md = new MarkdownIt()
let tokens = md.parse('# test')
console.log(tokens)
复制代码
markdown-it 提供了三种模式:commonmark、default、zero。分别对应最严格、GFM、最宽松的解析模式。json
markdown-it 的解析规则大致上分为块(block)和内联(inline)两种。具体可体现为 MarkdownIt.block
对应的是解析块规则的 ParserBlock, MarkdownIt.inline
对应的是解析内联规则的 ParserInline,MarkdownIt.renderer.render
和 MarkdownIt.renderer.renderInline
分别对应按照块规则和内联规则生成 HTML 代码。数组
在 MarkdownIt.renderer
中有一个特殊的属性:rules,它表明着对于 token 们的渲染规则,能够被使用者更新或扩展:浏览器
var md = require('markdown-it')();
md.renderer.rules.strong_open = function () { return '<b>'; };
md.renderer.rules.strong_close = function () { return '</b>'; };
var result = md.renderInline(...);
复制代码
好比这段代码就更新了渲染 strong_open 和 strong_close 这两种 token 的规则。
markdown-it 官方说过:
We do a markdown parser. It should keep the "markdown spirit". Other things should be kept separate, in plugins, for example. We have no clear criteria, sorry. Probably, you will find CommonMark forum a useful read to understand us better.
一言以蔽之,就是 markdown-it 只作纯粹的 markdown 解析,想要更多的功能你得本身写插件。
因此,他们提供了一个 API:MarkdownIt.use
它能够将指定的插件加载到当前的解析器实例中:
var iterator = require('markdown-it-for-inline');
var md = require('markdown-it')()
.use(iterator, 'foo_replace', 'text', function (tokens, idx) {
tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
});
复制代码
这段示例代码就将 markdown 代码中的 foo 所有替换成了 bar。
vuepress 借助了 markdown-it 的诸多社区插件,如高亮代码、代码块包裹、emoji 等,同时也自行编写了不少 markdown-it 插件,如识别 vue 组件、内外链区分渲染等。
本文写自 2018 年国庆期间,对应 vuepress 代码版本为 v1.0.0-alpha.4。
源码 主要作了下面五件事:
module.exports.dataReturnable = function dataReturnable (md) {
// override render to allow custom plugins return data
const render = md.render
md.render = (...args) => {
md.__data = {}
const html = render.call(md, ...args)
return {
html,
data: md.__data
}
}
}
复制代码
至关于让 __data 做为一个全局变量了,存储各个插件要用到的数据。
就作了一件事:替换默认的 htmlBlock 规则,这样就能够在根级别使用自定义的 vue 组件了。
module.exports = md => {
md.block.ruler.at('html_block', htmlBlock)
}
复制代码
这个 htmlBlock 函数和原生的 markdown-it 的 html_block 关键区别在哪呢?
答案是在 HTML_SEQUENCES 这个正则数组里添加了两个元素:
// PascalCase Components
[/^<[A-Z]/, />/, true],
// custom elements with hyphens
[/^<\w+\-/, />/, true],
复制代码
很明显,这就是用来匹配帕斯卡写法(如 <Button/>
)和连字符(如 <button-1/>
)写法的组件的。
这个组件其实是借助了社区的 markdown-it-container 插件,在此基础上定义了 tip、warning、danger、v-pre 这四种内容块的 render 函数:
render (tokens, idx) {
const token = tokens[idx]
const info = token.info.trim().slice(klass.length).trim()
if (token.nesting === 1) {
return `<div class="${klass} custom-block"><p class="custom-block-title">${info || defaultTitle}</p>\n`
} else {
return `</div>\n`
}
}
复制代码
这里须要说明一下的是 token 的两个属性。
info 三个反引号后面跟的那个字符串。
nesting 属性:
1
意味着标签打开。0
意味着标签是自动关闭的。-1
意味着标签正在关闭。if (lang === 'vue' || lang === 'html') {
lang = 'markup'
}
复制代码
function wrap (code, lang) {
if (lang === 'text') {
code = escapeHtml(code)
}
return `<pre v-pre class="language-${lang}"><code>${code}</code></pre>`
}
复制代码
const RE = /{([\d,-]+)}/
const lineNumbers = RE.exec(rawInfo)[1]
.split(',')
.map(v => v.split('-').map(v => parseInt(v, 10)))
复制代码
而后条件渲染:
if (inRange) {
return `<div class="highlighted"> </div>`
}
return '<br>'
复制代码
最后返回高亮行代码 + 普通代码。
重写 md.renderer.rules.html_block 规则:
const RE = /^<(script|style)(?=(\s|>|$))/i
md.renderer.rules.html_block = (tokens, idx) => {
const content = tokens[idx].content
const hoistedTags = md.__data.hoistedTags || (md.__data.hoistedTags = [])
if (RE.test(content.trim())) {
hoistedTags.push(content)
return ''
} else {
return content
}
}
复制代码
将 style 和 script 标签保存在 __data 这个伪全局变量里。这部分数据会在 markdownLoader 中用到。
重写 md.renderer.rules.fence 规则,经过换行符的数量来推算代码行数,并再包裹一层:
const lines = code.split('\n')
const lineNumbersCode = [...Array(lines.length - 1)]
.map((line, index) => `<span class="line-number">${index + 1}</span><br>`).join('')
const lineNumbersWrapperCode =
`<div class="line-numbers-wrapper">${lineNumbersCode}</div>`
复制代码
最后再获得最终代码:
const finalCode = rawCode
.replace('<!--beforeend-->', `${lineNumbersWrapperCode}<!--beforeend-->`)
.replace('extra-class', 'line-numbers-mode')
return finalCode
复制代码
一个 a 连接,多是跳往站内的,也有多是跳往站外的。vuepress 将这两种连接作了一个区分,最终外链会比内链多渲染出一个图标:
要实现这点,vuepress 重写了 md.renderer.rules.link_open 和 md.renderer.rules.link_close 这两个规则。
先看 md.renderer.rules.link_open :
if (isExternal) {
Object.entries(externalAttrs).forEach(([key, val]) => {
token.attrSet(key, val)
})
if (/_blank/i.test(externalAttrs['target'])) {
hasOpenExternalLink = true
}
} else if (isSourceLink) {
hasOpenRouterLink = true
tokens[idx] = toRouterLink(token, link)
}
复制代码
isExternal 即是外链的标志位,这时若是它为真,则直接设置 token 的属性便可,若是 isSourceLink 为真,则表明传入了个内链,整个 token 将会被替换成 toRouterLink(token, link)
:
function toRouterLink (token, link) {
link[0] = 'to'
let to = link[1]
// convert link to filename and export it for existence check
const links = md.__data.links || (md.__data.links = [])
links.push(to)
const indexMatch = to.match(indexRE)
if (indexMatch) {
const [, path, , hash] = indexMatch
to = path + hash
} else {
to = to
.replace(/\.md$/, '.html')
.replace(/\.md(#.*)$/, '.html$1')
}
// relative path usage.
if (!to.startsWith('/')) {
to = ensureBeginningDotSlash(to)
}
// markdown-it encodes the uri
link[1] = decodeURI(to)
// export the router links for testing
const routerLinks = md.__data.routerLinks || (md.__data.routerLinks = [])
routerLinks.push(to)
return Object.assign({}, token, {
tag: 'router-link'
})
}
复制代码
先是 href 被替换成 to,而后 to 又被替换成 .html 结尾的有效连接。
再来看 md.renderer.rules.link_close :
if (hasOpenRouterLink) {
token.tag = 'router-link'
hasOpenRouterLink = false
}
if (hasOpenExternalLink) {
hasOpenExternalLink = false
// add OutBoundLink to the beforeend of this link if it opens in _blank.
return '<OutboundLink/>' + self.renderToken(tokens, idx, options)
}
return self.renderToken(tokens, idx, options)
复制代码
很明显,内链渲染 router-link 标签,外链渲染 OutboundLink 标签,也就是加了那个小图标的连接组件。
这个插件重写了 md.renderer.rules.fence 方法,用来对 <pre>
标签再作一次包裹:
md.renderer.rules.fence = (...args) => {
const [tokens, idx] = args
const token = tokens[idx]
const rawCode = fence(...args)
return `<!--beforebegin--><div class="language-${token.info.trim()} extra-class">` +
`<!--afterbegin-->${rawCode}<!--beforeend--></div><!--afterend-->`
}
复制代码
将围栏代码拆成四个部分:beforebegin、afterbegin、beforeend、afterend。至关于给用户再自定义 markdown-it 插件提供了钩子。
这段代码最初是为了解决锚点中带中文或特殊字符没法正确跳转的问题。
处理的非 acsii 字符依次是:变音符号 -> C0控制符 -> 特殊字符 -> 连续出现2次以上的短杠(-) -> 用做开头或结尾的短杆。
最后将开头的数字加上下划线,所有转为小写。
它在 md.block.ruler.fence 以前加入了个 snippet 规则,用做解析 <<< @/filepath
这样的代码:
const start = pos + 3
const end = state.skipSpacesBack(max, pos)
const rawPath = state.src.slice(start, end).trim().replace(/^@/, root)
const filename = rawPath.split(/[{:\s]/).shift()
const content = fs.existsSync(filename) ? fs.readFileSync(filename).toString() : 'Not found: ' + filename
复制代码
它会把其中的文件路径拿出来和 root 路径拼起来,而后读取其中文件内容。由于还能够解析 <<< @/test/markdown/fragments/snippet.js{2}
这样附带行高亮的代码片断,因此须要用 split 截取真正的文件名。
markdown 做为一门解释型语言,能够帮助人们更好地描述一件事物。同时,它又做为通往 HTML 的桥梁,最终能够生成美观简约的页面。
而 markdown-it 提供的解析器、渲染器以及插件系统,更是让开发者能够根据本身的想象力赋予 markdown 更多的魅力。