388 字
2 分钟
vite支持custom-block功能显示源码
在写xinyi-ui的时候就想实现一个展示demo 并显示源代码的功能 了解到custom-block这个功能
这个问题折腾了我一整天,不过真是不负有心人,还好我没有放弃,现在对vite的原理不是很了解,只是记一下步骤,等以后再看吧
参考链接
在demo.vue 中添加自定义标签 如demo
<!--SwitchDemo--><demo>常规用法</demo>
<template> <Switch v-model:value="value" /></template>
<script lang="ts">import Switch from "../lib/Switch.vue";import { defineComponent, ref } from "vue";export default defineComponent({ name: "", setup() { const value = ref(true) return {value}; }, components: { Switch },});</script>实现插件获取源码 添加源码到组件
打印了好多东西才发现在请求这个添加了自定义块的vue的时候会有两个请求 而我要匹配的就是type=demo的那个请求

然后根据这个路径获取到源码 添加到组件的__sourCode属性上
如果style标签有内容的话 也会有type=style 的请求 这其中怎么分的 后面一定要了解下 tranform 函数怎么return 的不一样呢? 什么时候返回字符串 什么时候返回对象? 在plugin-vue 中对这种自定义块是怎么处理的?
const vueDemoPlugin = { name: 'vue-i18n', transform(code, path) { if (/vue&type=demo/.test(path)) { const file = fs.readFileSync(path.split('?')[0]).toString() const parsed = baseParse(file).children.find(n => n.tag === 'demo') const main = file.split(parsed.loc.source).join('').trim() return `export default Comp => { Comp.__sourceCode = ${JSON.stringify(main)} Comp.__sourceCodeTitle = ${JSON.stringify(code)} }` } }}组件中显示源码
在组件中引入SwitchDemo.vue
import SwitchDemo from 'xxx'console.log(SwtichDemo) // 发现SwitchDemo是一个对象 __sourceCode含有源码 vite支持custom-block功能显示源码
https://blog.cxyxiaoyu.top/posts/项目下支持custom-block功能显示源码/