refactor(md-loader): add robustness

This commit is contained in:
07akioni 2019-09-20 00:23:21 +08:00
parent e37a5bf465
commit 1e6549d271

View File

@ -30,7 +30,7 @@ renderer.code = (code, language) => {
: escapeForHTML(code)
// Render the highlighted code with `hljs` class.
return `<pre><code class="hljs ${language}">${highlighted}</code></pre>`
return `<pre><code class="${language}">${highlighted}</code></pre>`
}
marked.setOptions({
@ -52,22 +52,22 @@ function getPartsOfDemo (tokens) {
if (token.type === 'paragraph') {
content = token.text
}
if (token.type === 'code' && token.lang === 'html') {
if (token.type === 'code' && (token.lang === 'template' || token.lang === 'html')) {
template = token.text
}
if (token.type === 'code' && token.lang === 'js') {
if (token.type === 'code' && (token.lang === 'script' || token.lang === 'js')) {
script = token.text
}
if (token.type === 'code' && token.lang === 'css') {
if (token.type === 'code' && (token.lang === 'style' || token.lang === 'css')) {
style = token.text
}
}
return {
template,
script,
style,
title,
content
template: template,
script: script,
style: style,
title: title,
content: content
}
}
@ -78,6 +78,7 @@ function mergeParts (parts) {
mergedParts.title = parts.title
mergedParts.content = marked(parts.content)
mergedParts.code = ''
// console.log(parts)
if (parts.template) {
mergedParts.code += parts.template
}
@ -109,13 +110,24 @@ function genVueComponent (parts) {
const demoReg = /<!--DEMO_SLOT-->/
let src = demoBlock
// console.log(src)
src = src.replace(contentReg, parts.content)
src = src.replace(titleReg, parts.title)
src = src.replace(codeReg, parts.code)
src = src.replace(scriptReg, parts.script)
src = src.replace(styleReg, parts.style)
src = src.replace(demoReg, parts.template)
// console.log(src)
if (parts.content) {
src = src.replace(contentReg, parts.content)
}
if (parts.title) {
src = src.replace(titleReg, parts.title)
}
if (parts.code) {
src = src.replace(codeReg, parts.code)
}
if (parts.script) {
src = src.replace(scriptReg, parts.script)
}
if (parts.style) {
src = src.replace(styleReg, parts.style)
}
if (parts.template) {
src = src.replace(demoReg, parts.template)
}
return src.trim()
}
@ -124,15 +136,15 @@ function convertMd2Demo (text) {
const parts = getPartsOfDemo(tokens)
const mergedParts = mergeParts(parts)
const vueComponent = genVueComponent(mergedParts)
console.log(vueComponent)
// console.log(vueComponent)
return vueComponent
}
module.exports = convertMd2Demo
// const startTime = new Date()
// for (let i = 0; i < 100; ++i) {
// const md = fs.readFileSync('./marked/basic.md').toString()
// convertMd2Demo(md)
// const md = fs.readFileSync('./marked/basic.md').toString()
// convertMd2Demo(md)
// }
// const endTime = new Date()
// console.log(endTime - startTime)