返回 slidev
code-runners.ts
根目录 / demo / vue-runner / setup / code-runners.ts
1 /* eslint-disable no-new-func */
2 import { defineCodeRunnersSetup } from '@slidev/types'
3
4 export default defineCodeRunnersSetup(() => {
5 return {
6 // Support Vue SFC
7 async vue(code) {
8 const Vue = await import('vue')
9 const { parse, compileScript } = await import('@vue/compiler-sfc')
10
11 // Compile the script, note this demo does not handle Vue styles
12 const sfc = parse(code)
13 let scripts = compileScript(sfc.descriptor, {
14 id: sfc.descriptor.filename,
15 genDefaultAs: '__Component',
16 inlineTemplate: true,
17 }).content
18
19 // Replace Vue imports to object destructuring
20 // Only for simple demo, it doesn't work with imports from other packages
21 scripts = scripts.replace(/import (\{[^}]+\}) from ['"]vue['"]/g, (_, imports) => `const ${imports.replace(/\sas\s/g, ':')} = Vue`)
22 scripts += '\nreturn __Component'
23
24 // Create function to evaluate the script and get the component
25 // Note this is not sandboxed, it's NOT secure.
26 const component = new Function(`return (Vue) => {${scripts}}`)()(Vue)
27
28 // Mount the component
29 const app = Vue.createApp(component)
30 const el = document.createElement('div')
31 app.mount(el)
32
33 return {
34 element: el,
35 }
36 },
37 }
38 })
39
39 lines TYPESCRIPT