自定义loader展示.vue文件代码

vite.config.ts

  1. import vue from '@vitejs/plugin-vue'
  2. import {md} from './plugins/md'
  3. import fs from 'fs'
  4. import {baseParse} from '@vue/compiler-core'
  5. // https://vitejs.dev/config/
  6. export default {
  7. plugins: [vue({
  8. include: [/\.vue$/, /\.md$/], // <--
  9. }), md()]
  10. ,
  11. vueCustomBlockTransforms: {
  12. demo: (options) => {
  13. const { code, path } = options
  14. const file = fs.readFileSync(path).toString()
  15. const parsed = baseParse(file).children.find(n => n.tag === 'demo')
  16. const title = parsed.children[0].content
  17. const main = file.split(parsed.loc.source).join('').trim()
  18. return `export default function (Component) {
  19. Component.__sourceCode = ${
  20. JSON.stringify(main)
  21. }
  22. Component.__sourceCodeTitle = ${JSON.stringify(title)}
  23. }`.trim()
  24. }
  25. }
  26. }

在需要展示代码的vue中间中加入自定义块custom block

  1. <demo>
  2. 支持disabled
  3. </demo>
  4. <template>
  5. </template>
  6. // ...

import 组件文件后, 获取代码

  1. import Switch1Demo from './Switch1.demo.vue'
  2. import Switch2Demo from './Switch2.demo.vue'
  3. import {ref} from 'vue'
  4. export default {
  5. setup(){
  6. const bool = ref(false)
  7. return {
  8. bool,
  9. Switch1Demo,
  10. Switch2Demo
  11. }
  12. },
  13. }
  1. <div class="demo-code">
  2. <pre>{{Switch1Demo.__sourceCode}}</pre>
  3. </div>

使用component动态加载组件

在setup中返回的组件的名或组件对象,可以通过component标签动态加载

  1. <component :is="Switch1Demo" />