-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
export-expose.ts
97 lines (87 loc) · 2.31 KB
/
export-expose.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
97
import { FileKind } from '@volar/language-core'
import {
FileRangeCapabilities,
type Segment,
type Sfc,
type VueEmbeddedFile,
type VueLanguagePlugin,
replace,
replaceSourceRange,
} from '@volar/vue-language-core'
import { createFilter } from '@rollup/pluginutils'
import { type VolarOptions } from '..'
import { getVolarOptions } from './common'
function transform({
fileName,
file,
sfc,
ts,
volarOptions,
}: {
fileName: string
file: VueEmbeddedFile
sfc: Sfc
ts: typeof import('typescript/lib/tsserverlibrary')
volarOptions: NonNullable<VolarOptions['exportExpose']>
}) {
const filter = createFilter(
volarOptions.include || /.*/,
volarOptions.exclude
)
if (!filter(fileName)) return
const exposed: Record<string, Segment<FileRangeCapabilities>> = {}
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)
for (const decl of stmt.declarationList.declarations) {
if (!ts.isIdentifier(decl.name)) continue
const name = decl.name.text
const start = decl.name.getStart(sfc.scriptSetupAst!)
exposed[name] = [name, 'scriptSetup', start, FileRangeCapabilities.full]
}
}
if (Object.keys(exposed).length === 0) return
const exposedStrings = Object.entries(exposed).flatMap(([key, value]) => [
`${key}: `,
value,
',\n',
])
replace(
file.content,
'return {\n',
'return {\n...{ ',
...exposedStrings,
' },\n'
)
}
const plugin: VueLanguagePlugin = ({
vueCompilerOptions,
modules: { typescript: ts },
}) => {
return {
name: 'vue-macros-export-expose',
version: 1,
resolveEmbeddedFile(fileName, sfc, embeddedFile) {
if (
embeddedFile.kind !== FileKind.TypeScriptHostFile ||
!sfc.scriptSetup ||
!sfc.scriptSetupAst
)
return
transform({
fileName,
file: embeddedFile,
sfc,
ts,
volarOptions: getVolarOptions(vueCompilerOptions)?.exportExpose || {},
})
},
}
}
export = plugin