-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
importAnaysisBuild.ts
388 lines (356 loc) · 11.4 KB
/
importAnaysisBuild.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import path from 'path'
import glob from 'fast-glob'
import { ResolvedConfig } from '../config'
import { Plugin } from '../plugin'
import { cleanUrl } from '../utils'
import MagicString from 'magic-string'
import { ImportSpecifier, init, parse as parseImports } from 'es-module-lexer'
import { RollupError, OutputChunk } from 'rollup'
import { chunkToEmittedCssFileMap } from './css'
/**
* A flag for injected helpers. This flag will be set to `false` if the output
* target is not native es - so that injected helper logic can be conditinally
* dropped.
*/
export const isModernFlag = `__VITE_IS_MODERN__`
const preloadHelperId = 'vite/preload-helper'
const preloadMethod = __vitePreload.name
const preloadModuleCode = `const seen = {};export ${__vitePreload.toString()}`
const preloadMarker = `__VITE_PRELOAD__`
const preloadMarkerRE = new RegExp(`,?"${preloadMarker}"`, 'g')
/**
* Helper for preloading CSS and direct imports of async chunks in parallell to
* the async chunk itself.
*/
function __vitePreload(baseModule: () => Promise<{}>, deps?: string[]) {
// @ts-ignore
if (!__VITE_IS_MODERN__ || !deps) {
return baseModule()
}
return Promise.all(
deps.map((dep) => {
// @ts-ignore
if (dep in seen) return
// @ts-ignore
seen[dep] = true
const isCss = /\.css$/.test(dep)
// @ts-ignore check if the file is already preloaded by SSR markup
if (document.querySelector(`link[href="${dep}"]`)) {
return
}
// @ts-ignore
const link = document.createElement('link')
link.rel = isCss
? 'stylesheet'
: link.relList &&
link.relList.supports &&
link.relList.supports('modulepreload')
? 'modulepreload'
: 'preload'
if (!isCss) {
link.as = 'script'
link.crossOrigin = ''
}
link.href = dep
// @ts-ignore
document.head.appendChild(link)
if (isCss) {
return new Promise((res) => {
link.addEventListener('load', res)
})
}
})
).then(() => baseModule())
}
/**
* Build only. During serve this is performed as part of ./importAnalysis.
*/
export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:import-analysis',
resolveId(id) {
if (id === preloadHelperId) {
return id
}
},
load(id) {
if (id === preloadHelperId) {
return preloadModuleCode
}
},
async transform(source, importer, ssr) {
if (ssr || importer.includes('node_modules')) {
return
}
await init
let imports: ImportSpecifier[] = []
try {
imports = parseImports(source)[0]
} catch (e) {
this.error(e, e.idx)
}
if (!imports.length) {
return null
}
let s: MagicString | undefined
const str = () => s || (s = new MagicString(source))
let hasInjectedHelper = false
for (let index = 0; index < imports.length; index++) {
const { s: start, e: end, ss: expStart, d: dynamicIndex } = imports[
index
]
const isGlob =
source.slice(start, end) === 'import.meta' &&
source.slice(end, end + 5) === '.glob'
if (isGlob || dynamicIndex > -1) {
// inject parallelPreload helper.
if (!hasInjectedHelper) {
hasInjectedHelper = true
str().prepend(
`import { ${preloadMethod} } from "${preloadHelperId}";`
)
}
}
// import.meta.glob
if (isGlob) {
const { imports, exp, endIndex } = await transformImportGlob(
source,
start,
importer,
index
)
str().prepend(imports)
str().overwrite(expStart, endIndex, exp)
continue
}
if (dynamicIndex > -1) {
const dynamicEnd = source.indexOf(`)`, end) + 1
const original = source.slice(dynamicIndex, dynamicEnd)
let replacement =
`(${isModernFlag} ` +
`? ${preloadMethod}(() => ${original},"${preloadMarker}")` +
` : ${original})`
// backtrace to see if the import call is after a newline
for (let i = dynamicIndex - 1; i > 0; i--) {
const char = source.charAt(i)
if (char === '\n') {
replacement = `;` + replacement
break
} else if (!/\s/.test(char)) {
break
}
}
str().overwrite(dynamicIndex, dynamicEnd, replacement)
}
}
if (s) {
return {
code: s.toString(),
map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
}
}
},
renderChunk(code, _, { format }) {
// make sure we only perform the preload logic in modern builds.
if (code.indexOf(isModernFlag) > -1) {
return code.replace(/__VITE_IS_MODERN__/g, String(format === 'es'))
}
return null
},
generateBundle({ format }, bundle) {
if (format !== 'es') {
return
}
const isPolyfillEnabled = config.build.polyfillDynamicImport
for (const file in bundle) {
const chunk = bundle[file]
// can't use chunk.dynamicImports.length here since some modules e.g.
// dynamic import to constant json may get inlined.
if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
const code = chunk.code
let imports: ImportSpecifier[]
try {
imports = parseImports(code)[0]
} catch (e) {
this.error(e, e.idx)
}
if (imports.length) {
const s = new MagicString(code)
for (let index = 0; index < imports.length; index++) {
const { s: start, e: end, d: dynamicIndex } = imports[index]
if (dynamicIndex > -1) {
// if dynmamic import polyfill is used, rewrite the import to
// use the polyfilled function.
if (isPolyfillEnabled) {
s.overwrite(dynamicIndex, dynamicIndex + 6, `__import__`)
}
// check the chunk being imported
const url = code.slice(start, end)
const deps: Set<string> = new Set()
if (url[0] === `"` && url[url.length - 1] === `"`) {
const ownerFilename = chunk.fileName
// literal import - trace direct imports and add to deps
const addDeps = (filename: string) => {
if (filename === ownerFilename) return
const chunk = bundle[filename] as OutputChunk | undefined
if (chunk) {
deps.add(config.build.base + chunk.fileName)
const cssId = chunkToEmittedCssFileMap.get(chunk)
if (cssId) {
deps.add(config.build.base + this.getFileName(cssId))
}
chunk.imports.forEach(addDeps)
}
}
const normalizedFile = path.posix.join(
path.posix.dirname(chunk.fileName),
url.slice(1, -1)
)
addDeps(normalizedFile)
}
const markPos = code.indexOf(preloadMarker, end)
s.overwrite(
markPos - 1,
markPos + preloadMarker.length + 1,
// the dep list includes the main chunk, so only need to
// preload when there are actual other deps.
deps.size > 1
? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]`
: `void 0`
)
}
}
chunk.code = s.toString()
// TODO source map
} else {
// inlined dynamic import, remove the marker
chunk.code = code.replace(preloadMarkerRE, 'void 0')
}
}
}
}
}
}
export async function transformImportGlob(
source: string,
pos: number,
importer: string,
importIndex: number,
normalizeUrl?: (url: string, pos: number) => Promise<[string, string]>
): Promise<{ imports: string; exp: string; endIndex: number }> {
const err = (msg: string) => {
const e = new Error(`Invalid glob import syntax: ${msg}`)
;(e as any).pos = pos
return e
}
importer = cleanUrl(importer)
const importerBasename = path.basename(importer)
let [pattern, endIndex] = lexGlobPattern(source, pos)
if (!pattern.startsWith('.')) {
throw err(`pattern must start with "."`)
}
let base = path.dirname(importer)
let parentDepth = 0
while (pattern.startsWith('../')) {
pattern = pattern.slice(3)
base = path.resolve(base, '../')
parentDepth++
}
if (pattern.startsWith('./')) {
pattern = pattern.slice(2)
}
const files = glob.sync(pattern, { cwd: base })
let imports = ``
let entries = ``
for (let i = 0; i < files.length; i++) {
// skip importer itself
if (files[i] === importerBasename) continue
const file = parentDepth
? `${'../'.repeat(parentDepth)}${files[i]}`
: `./${files[i]}`
let importee = file
if (normalizeUrl) {
;[importee] = await normalizeUrl(file, pos)
}
const identifier = `__glob_${importIndex}_${i}`
const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager'
if (isEager) {
imports += `import * as ${identifier} from ${JSON.stringify(importee)};`
entries += ` ${JSON.stringify(file)}: ${identifier},`
} else {
let imp = `import(${JSON.stringify(importee)})`
if (!normalizeUrl) {
imp =
`(${isModernFlag}` +
`? ${preloadMethod}(()=>${imp},"${preloadMarker}")` +
`: ${imp})`
}
entries += ` ${JSON.stringify(file)}: () => ${imp},`
}
}
return {
imports,
exp: `{${entries}}`,
endIndex
}
}
const enum LexerState {
inCall,
inSingleQuoteString,
inDoubleQuoteString,
inTemplateString
}
function lexGlobPattern(code: string, pos: number): [string, number] {
let state = LexerState.inCall
let pattern = ''
let i = code.indexOf(`(`, pos) + 1
outer: for (; i < code.length; i++) {
const char = code.charAt(i)
switch (state) {
case LexerState.inCall:
if (char === `'`) {
state = LexerState.inSingleQuoteString
} else if (char === `"`) {
state = LexerState.inDoubleQuoteString
} else if (char === '`') {
state = LexerState.inTemplateString
} else if (/\s/.test(char)) {
continue
} else {
error(i)
}
break
case LexerState.inSingleQuoteString:
if (char === `'`) {
break outer
} else {
pattern += char
}
break
case LexerState.inDoubleQuoteString:
if (char === `"`) {
break outer
} else {
pattern += char
}
break
case LexerState.inTemplateString:
if (char === '`') {
break outer
} else {
pattern += char
}
break
default:
throw new Error('unknown import.meta.glob lexer state')
}
}
return [pattern, code.indexOf(`)`, i) + 1]
}
function error(pos: number) {
const err = new Error(
`import.meta.glob() can only accept string literals.`
) as RollupError
err.pos = pos
throw err
}