越努力,越幸运,做个ccode~

0%

vite支持custom-block功能显示源码

在写xinyi-ui的时候就想实现一个展示demo 并显示源代码的功能 了解到custom-block这个功能

这个问题折腾了我一整天,不过真是不负有心人,还好我没有放弃,现在对vite的原理不是很了解,只是记一下步骤,等以后再看吧

参考链接

在demo.vue 中添加自定义标签 如demo

1
<!--SwitchDemo-->
2
<demo>常规用法</demo>
3
4
<template>
5
   <Switch v-model:value="value" />
6
</template>
7
8
<script lang="ts">
9
import Switch from "../lib/Switch.vue";
10
import { defineComponent, ref } from "vue";
11
export default defineComponent({
12
  name: "",
13
  setup() {
14
    const value = ref(true)
15
    return {value};
16
  },
17
  components: { Switch },
18
});
19
</script>

实现插件获取源码 添加源码到组件

打印了好多东西才发现在请求这个添加了自定义块的vue的时候会有两个请求 而我要匹配的就是type=demo的那个请求

然后根据这个路径获取到源码 添加到组件的__sourCode属性上

如果style标签有内容的话 也会有type=style 的请求 这其中怎么分的 后面一定要了解下
tranform 函数怎么return 的不一样呢? 什么时候返回字符串 什么时候返回对象?
在plugin-vue 中对这种自定义块是怎么处理的?

1
const vueDemoPlugin = {
2
  name: 'vue-i18n',
3
  transform(code, path) {
4
    if (/vue&type=demo/.test(path)) {
5
      const file = fs.readFileSync(path.split('?')[0]).toString()
6
      const parsed = baseParse(file).children.find(n => n.tag === 'demo')
7
      const main = file.split(parsed.loc.source).join('').trim()
8
      return `export default Comp => { 
9
        Comp.__sourceCode = ${JSON.stringify(main)} 
10
        Comp.__sourceCodeTitle = ${JSON.stringify(code)}   
11
      }`
12
    }
13
  }
14
}

组件中显示源码

在组件中引入SwitchDemo.vue

1
import SwitchDemo from 'xxx'
2
console.log(SwtichDemo)  // 发现SwitchDemo是一个对象 __sourceCode含有源码