自定义loader展示.vue文件代码
vite.config.ts
import vue from '@vitejs/plugin-vue'
import {md} from './plugins/md'
import fs from 'fs'
import {baseParse} from '@vue/compiler-core'
// https://vitejs.dev/config/
export default {
plugins: [vue({
include: [/\.vue$/, /\.md$/], // <--
}), md()]
,
vueCustomBlockTransforms: {
demo: (options) => {
const { code, path } = options
const file = fs.readFileSync(path).toString()
const parsed = baseParse(file).children.find(n => n.tag === 'demo')
const title = parsed.children[0].content
const main = file.split(parsed.loc.source).join('').trim()
return `export default function (Component) {
Component.__sourceCode = ${
JSON.stringify(main)
}
Component.__sourceCodeTitle = ${JSON.stringify(title)}
}`.trim()
}
}
}
在需要展示代码的vue中间中加入自定义块custom block
<demo>
支持disabled
</demo>
<template>
</template>
// ...
import 组件文件后, 获取代码
import Switch1Demo from './Switch1.demo.vue'
import Switch2Demo from './Switch2.demo.vue'
import {ref} from 'vue'
export default {
setup(){
const bool = ref(false)
return {
bool,
Switch1Demo,
Switch2Demo
}
},
}
<div class="demo-code">
<pre>{{Switch1Demo.__sourceCode}}</pre>
</div>
使用component动态加载组件
在setup中返回的组件的名或组件对象,可以通过component标签动态加载
<component :is="Switch1Demo" />