癥結(jié)(懶癌患者)
在寫(xiě)組件庫(kù)文檔的時(shí)候,會(huì)把示例代碼粘貼到文檔里,這樣做有一個(gè)很惡心的地方:每次組件迭代或修改示例都需要重新修改文檔中的代碼片段。長(zhǎng)年累月,苦不堪言。
猜想(狂想曲)
所以我想,可不可以把.vue文件里的template塊和script塊取出來(lái),放入對(duì)應(yīng)的.md文件中
比如在.md文件中 {{:xx.vue?type=(template|script)}} 便替換示例中對(duì)應(yīng)的template|script塊
# xx## 示例代碼// {{:}} 定義變量規(guī)則模版(加個(gè)冒號(hào)防沖突){{:image.vue?type=template}} // 對(duì)應(yīng).vue 的template{{:image.vue?type=script}} // 對(duì)應(yīng).vue 的template{{:index.js}} // 對(duì)應(yīng)index.js## 參數(shù)說(shuō)明xxx...output
# xx## 示例代碼 // image.vue template<template> <div>xx</div></template>// image.vue script<script> ...</script>// index.jsvar x = 1## 參數(shù)說(shuō)明xxx...
動(dòng)手(能動(dòng)手絕不**)
要實(shí)現(xiàn)以上功能,需要探索以下幾點(diǎn):
從.vue里取出template&script 塞進(jìn)對(duì)應(yīng)的.md的變量位置 將.md文件轉(zhuǎn)為Vue Componet / html如果按照我們寫(xiě)js的習(xí)慣,以下嵌套排列可能更易讀
將.md文件轉(zhuǎn)為Vue Componet / html
找到變量位置,塞進(jìn)對(duì)應(yīng)的.md的指定位置
從.vue里取出template&script
一步一步來(lái)吧:
1、將.md文件轉(zhuǎn)為Vue Componet / html
要想在vue中使用.md文件為組件,只需要用loader將md轉(zhuǎn)成Vue Componet即可。
這個(gè)過(guò)程很簡(jiǎn)單,以下為loader偽代碼
const wrapper = content => `<template> <section v-html="content" v-once /></template><script>export default { created() { this.content = content }};</script>`module.exports = function(source) { // markdown 編譯用的 markdown-it return wrapper(new MarkdownIt().render(source)) }2、找到變量位置,塞進(jìn)對(duì)應(yīng)的.md的指定位置
1)找到變量位置
使用正則匹配定義的規(guī)則,找到被{{:}} 包圍的字符串,如上例所示則為‘image.vue?type=template'
2)讀取文件
如果是其他.js、.html等普通文件,直接使用fs.readFileSync讀取替換即可,因是.vue,我們希望傳入type來(lái)獲取不同的塊(template、script等)
const replaceResults = (template, baseDir) => { const regexp = new RegExp("http://{//{:([^//}]+)//}//}", "g") return template.replace(regexp, function(match) { // 獲取文件變量 match = match.substr(3, match.length - 5) let [loadFile, query=''] = match.split('?') // 讀取文件內(nèi)容 const source = fs.readFileSync(path.join(baseDir, loadFile), "utf-8").replace(/[/r/n]*$/, "") if (path.extname(loadFile) === ".vue") { let { type } = loaderUtils.parseQuery(`?${query}`) return replaceVue(source, type) // 根據(jù)type提取.vue里的不同塊 } return source // 非.vue直接返回文件內(nèi)容 })};
新聞熱點(diǎn)
疑難解答
圖片精選