-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
export-expose.ts
99 lines (89 loc) · 2.41 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
98
99
import { FileKind } from '@volar/language-core'
import {
FileRangeCapabilities,
type Segment,
type Sfc,
type VueLanguagePlugin,
replaceAll,
replaceSourceRange,
} from '@vue/language-core'
import { createFilter } from '@rollup/pluginutils'
import { getVolarOptions } from './common'
import type { VueEmbeddedFile } from '@vue/language-core/out/virtualFile/embeddedFile'
import type { VolarOptions } from '..'
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>> = Object.create(
null
)
for (const stmt of sfc.scriptSetup!.ast.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.scriptSetup?.ast)
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.scriptSetup?.ast)
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',
])
replaceAll(
file.content,
/return {\n/g,
'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.scriptSetup.ast
)
return
transform({
fileName,
file: embeddedFile,
sfc,
ts,
volarOptions: getVolarOptions(vueCompilerOptions)?.exportExpose || {},
})
},
}
}
export default plugin