forked from vitejs/vite
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dynamicImportVars.ts
245 lines (212 loc) · 6.26 KB
/
dynamicImportVars.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { posix } from 'node:path'
import MagicString from 'magic-string'
import { init, parse as parseImports } from 'es-module-lexer'
import type { ImportSpecifier } from 'es-module-lexer'
import { parse as parseJS } from 'acorn'
import { dynamicImportToGlob } from '@rollup/plugin-dynamic-import-vars'
import type { KnownAsTypeMap } from 'types/importGlob'
import type { Plugin } from '../plugin'
import type { ResolvedConfig } from '../config'
import {
createFilter,
normalizePath,
parseRequest,
removeComments,
requestQuerySplitRE,
transformStableResult,
} from '../utils'
import { toAbsoluteGlob } from './importMetaGlob'
export const dynamicImportHelperId = '\0vite/dynamic-import-helper'
interface DynamicImportRequest {
as?: keyof KnownAsTypeMap
}
interface DynamicImportPattern {
globParams: DynamicImportRequest | null
userPattern: string
rawPattern: string
}
const dynamicImportHelper = (glob: Record<string, any>, path: string) => {
const v = glob[path]
if (v) {
return typeof v === 'function' ? v() : Promise.resolve(v)
}
return new Promise((_, reject) => {
;(typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
reject.bind(null, new Error('Unknown variable dynamic import: ' + path)),
)
})
}
function parseDynamicImportPattern(
strings: string,
): DynamicImportPattern | null {
const filename = strings.slice(1, -1)
const rawQuery = parseRequest(filename)
let globParams: DynamicImportRequest | null = null
const ast = (
parseJS(strings, {
ecmaVersion: 'latest',
sourceType: 'module',
}) as any
).body[0].expression
const userPatternQuery = dynamicImportToGlob(ast, filename)
if (!userPatternQuery) {
return null
}
const [userPattern] = userPatternQuery.split(requestQuerySplitRE, 2)
const [rawPattern] = filename.split(requestQuerySplitRE, 2)
if (rawQuery?.raw !== undefined) {
globParams = { as: 'raw' }
}
if (rawQuery?.url !== undefined) {
globParams = { as: 'url' }
}
if (rawQuery?.worker !== undefined) {
globParams = { as: 'worker' }
}
return {
globParams,
userPattern,
rawPattern,
}
}
export async function transformDynamicImport(
importSource: string,
importer: string,
resolve: (
url: string,
importer?: string,
) => Promise<string | undefined> | string | undefined,
root: string,
): Promise<{
glob: string
pattern: string
rawPattern: string
} | null> {
if (importSource[1] !== '.' && importSource[1] !== '/') {
const resolvedFileName = await resolve(importSource.slice(1, -1), importer)
if (!resolvedFileName) {
return null
}
const relativeFileName = posix.relative(
posix.dirname(normalizePath(importer)),
normalizePath(resolvedFileName),
)
importSource = normalizePath(
'`' + (relativeFileName[0] === '.' ? '' : './') + relativeFileName + '`',
)
}
const dynamicImportPattern = parseDynamicImportPattern(importSource)
if (!dynamicImportPattern) {
return null
}
const { globParams, rawPattern, userPattern } = dynamicImportPattern
const params = globParams
? `, ${JSON.stringify({ ...globParams, import: '*' })}`
: ''
let newRawPattern = posix.relative(
posix.dirname(importer),
await toAbsoluteGlob(rawPattern, root, importer, resolve),
)
if (!/^\.{1,2}\//.test(newRawPattern)) {
newRawPattern = `./${newRawPattern}`
}
const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`
return {
rawPattern: newRawPattern,
pattern: userPattern,
glob: exp,
}
}
export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
const resolve = config.createResolver({
preferRelative: true,
tryIndex: false,
extensions: [],
})
const { include, exclude, warnOnError } =
config.build.dynamicImportVarsOptions
const filter = createFilter(include, exclude)
return {
name: 'vite:dynamic-import-vars',
resolveId(id) {
if (id === dynamicImportHelperId) {
return id
}
},
load(id) {
if (id === dynamicImportHelperId) {
return 'export default ' + dynamicImportHelper.toString()
}
},
async transform(source, importer) {
if (!filter(importer)) {
return
}
await init
let imports: readonly ImportSpecifier[] = []
try {
imports = parseImports(source)[0]
} catch (e: any) {
// ignore as it might not be a JS file, the subsequent plugins will catch the error
return null
}
if (!imports.length) {
return null
}
let s: MagicString | undefined
let needDynamicImportHelper = false
for (let index = 0; index < imports.length; index++) {
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
d: dynamicIndex,
} = imports[index]
if (dynamicIndex === -1 || source[start] !== '`') {
continue
}
s ||= new MagicString(source)
let result
try {
// When import string is using backticks, es-module-lexer `end` captures
// until the closing parenthesis, instead of the closing backtick.
// There may be inline comments between the backtick and the closing
// parenthesis, so we manually remove them for now.
// See https://github.com/guybedford/es-module-lexer/issues/118
const importSource = removeComments(source.slice(start, end)).trim()
result = await transformDynamicImport(
importSource,
importer,
resolve,
config.root,
)
} catch (error) {
if (warnOnError) {
this.warn(error)
} else {
this.error(error)
}
}
if (!result) {
continue
}
const { rawPattern, glob } = result
needDynamicImportHelper = true
s.overwrite(
expStart,
expEnd,
`__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`,
)
}
if (s) {
if (needDynamicImportHelper) {
s.prepend(
`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`,
)
}
return transformStableResult(s, importer, config)
}
},
}
}