-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathvite-plugin-setup-name.ts
44 lines (41 loc) · 1.39 KB
/
vite-plugin-setup-name.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import MagicString from 'magic-string'
import { parse, compileScript } from '@vue/compiler-sfc'
// import { basename } from 'path'
import type { Plugin } from 'vite'
export default (): Plugin => {
return {
name: 'vite:my-plugin',
enforce: 'pre',
transform(source, id) {
if (/.vue$/.test(id) || /.vue\?.&type=script.*/.test(id)) {
let s: MagicString | undefined
const str = () => s || (s = new MagicString(source))
const { descriptor } = parse(source)
if (!descriptor.script && descriptor.scriptSetup && !descriptor.scriptSetup.attrs?.extendIgnore) {
const result = compileScript(descriptor, { id })
const { name = '', lang, inheritAttrs } = result.attrs
if (name || inheritAttrs) {
str().appendLeft(
0,
`<script ${lang ? `lang="${lang}"` : ''}>
import { defineComponent } from 'vue'
export default defineComponent({
${name ? `name: "${name}",` : ''}
${inheritAttrs ? `inheritAttrs: ${inheritAttrs !== 'false'},` : ''}
})
</script>\n`
)
}
const map = str().generateMap({ hires: true })
// const filename = basename(id)
return {
map,
code: str().toString(),
}
}
} else {
return null
}
},
}
}