vue组件文档(.md)中如何自动导入示例(.vue)详解

2020-06-14 06:15:17易采站长站整理

// 获取文件变量
match = match.substr(3, match.length - 5)
let [loadFile, query=''] = match.split('?')
// 读取文件内容
const source = fs.readFileSync(path.join(baseDir, loadFile), "utf-8").replace(/[rn]*$/, "")
if (path.extname(loadFile) === ".vue") {
let { type } = loaderUtils.parseQuery(`?${query}`)
return replaceVue(source, type) // 根据type提取.vue里的不同块
}
return source // 非.vue直接返回文件内容
})
};

3、从.vue里取出template&script


const replaceVue = (source, type) => {
const descriptor = templateCompiler.parseComponent(source)
const lang = {
template: 'html',
script: 'javascript' //,
// style: 'css'
}
return lang[type] && `
```${lang[type]}
${descriptor[type].content}
```
`
}

如若要取一个文件里的多个块,则需多次调用,考虑到我们的组件库场景,默认返回template和script(未使用type参数时),
对上面代码进行优化,一次性从.vue中取出多个块


// replaceVue(source, [type])
const replaceVue = (source, types = ['template', 'script']) => {
const descriptor = templateCompiler.parseComponent(source)
const lang = {
template: 'html',
script: 'javascript' //,
// style: 'css'
}
return types.map(type => lang[type] && `
```${lang[type]}
${descriptor[type].content}
```
`).join('')
}

大功告成🎉🎉! 那么,如何使用呢?

使用(给我小星星🌟)

安装


npm i vue-markd-loader -D

配置


rules: [{
test: /.md$/,
use: [
'vue-loader',
{
loader: 'vue-markd-loader',
options: {
replaceFiles: true , // 默认true, 是否将文件填充进md
wrapper:true // 默认true,默认输出Vue Component ,false 时输出html片段
}
}
] }]


// main.js
import 'highlight.js/styles/github.css' // 可以使用任意喜欢的主题哟
import 'github-markdown-css'

其他

第一次撸webpack loader,如有不正确/不足的地方,欢迎指正。

源代码git地址 (本地下载)
npm包地址

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。