-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
export-props.ts
96 lines (88 loc) · 2.29 KB
/
export-props.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { FileKind } from '@volar/language-core'
import {
type Sfc,
type VueEmbeddedFile,
type VueLanguagePlugin,
replaceSourceRange,
} from '@volar/vue-language-core'
import { createFilter } from '@rollup/pluginutils'
import { type VolarOptions } from '..'
import { addProps, getVolarOptions, getVueLibraryName } from './common'
function transform({
file,
sfc,
ts,
vueLibName,
volarOptions,
fileName,
}: {
fileName: string
file: VueEmbeddedFile
sfc: Sfc
ts: typeof import('typescript/lib/tsserverlibrary')
vueLibName: string
volarOptions: NonNullable<VolarOptions['exportProps']>
}) {
const filter = createFilter(
volarOptions.include || /.*/,
volarOptions.exclude
)
if (!filter(fileName)) return
const props: Record<string, boolean> = {}
let changed = false
for (const stmt of sfc.scriptSetupAst!.statements) {
if (!ts.isVariableStatement(stmt)) continue
const exportModifier = stmt.modifiers?.find(
(m) => m.kind === ts.SyntaxKind.ExportKeyword
)
if (!exportModifier) continue
const start = exportModifier.getStart(sfc.scriptSetupAst!)
const end = exportModifier.getEnd()
replaceSourceRange(file.content, 'scriptSetup', start, end)
changed = true
for (const decl of stmt.declarationList.declarations) {
if (!ts.isIdentifier(decl.name)) continue
props[decl.name.text] = !!decl.initializer
}
}
if (changed) {
addProps(
file.content,
[
`__VLS_TypePropsToRuntimeProps<{
${Object.entries(props)
.map(([prop, optional]) => ` ${prop}${optional ? '?' : ''}: typeof ${prop}`)
.join(',\n')}
}>`,
],
vueLibName
)
}
}
const plugin: VueLanguagePlugin = ({
modules: { typescript: ts },
vueCompilerOptions,
}) => {
return {
name: 'vue-macros-export-props',
version: 1,
resolveEmbeddedFile(fileName, sfc, embeddedFile) {
if (
embeddedFile.kind !== FileKind.TypeScriptHostFile ||
!sfc.scriptSetup ||
!sfc.scriptSetupAst
)
return
const vueLibName = getVueLibraryName(vueCompilerOptions.target)
transform({
file: embeddedFile,
sfc,
vueLibName,
ts,
fileName,
volarOptions: getVolarOptions(vueCompilerOptions)?.exportProps || {},
})
},
}
}
export = plugin