chore: add vant-markdown-loader package

This commit is contained in:
陈嘉涵
2019-08-21 14:45:40 +08:00
parent 2e537b1c81
commit f9b89ad53e
6 changed files with 613 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
module.exports = function cardWrapper(html) {
const group = html.replace(/<h3/g, ':::<h3').replace(/<h2/g, ':::<h2').split(':::');
return group
.map(fragment => {
if (fragment.indexOf('<h3') !== -1) {
return `<div class="card">${fragment}</div>`;
}
return fragment;
})
.join('');
};

View File

@@ -0,0 +1,9 @@
const hljs = require('highlight.js');
module.exports = function highlight(str, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(lang, str, true).value;
}
return '';
};

View File

@@ -0,0 +1,72 @@
const loaderUtils = require('loader-utils');
const MarkdownIt = require('markdown-it');
const markdownItAnchor = require('markdown-it-anchor');
const frontMatter = require('front-matter');
const highlight = require('./highlight');
const cardWrapper = require('./card-wrapper');
const { slugify } = require('transliteration');
function wrapper(content) {
content = cardWrapper(content);
content = escape(content);
return `
<template>
<section v-html="content" v-once />
</template>
<script>
export default {
created() {
this.content = unescape(\`${content}\`);
},
mounted() {
const anchors = [].slice.call(this.$el.querySelectorAll('h2, h3, h4, h5'));
anchors.forEach(anchor => {
anchor.addEventListener('click', this.scrollToAnchor);
});
},
methods: {
scrollToAnchor(event) {
if (event.target.id) {
this.$router.push({
path: this.$route.path,
hash: event.target.id
})
}
}
}
};
</script>
`;
}
const parser = new MarkdownIt({
html: true,
highlight
}).use(markdownItAnchor, {
level: 2,
slugify
});
module.exports = function(source) {
let options = loaderUtils.getOptions(this) || {};
this.cacheable && this.cacheable();
options = {
wrapper,
...options
};
let fm;
if (options.enableMetaData) {
fm = frontMatter(source);
source = fm.body;
}
return options.wrapper(parser.render(source), fm);
};