forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
702 lines (629 loc) · 19.3 KB
/
index.js
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
// @ts-check
const path = require('path')
const { createHash } = require('crypto')
const { build } = require('vite')
const MagicString = require('magic-string').default
// lazy load babel since it's not used during dev
let babel
/**
* @return {import('@babel/standalone')}
*/
const loadBabel = () => babel || (babel = require('@babel/standalone'))
// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
// DO NOT ALTER THIS CONTENT
const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`
const legacyPolyfillId = 'vite-legacy-polyfill'
const legacyEntryId = 'vite-legacy-entry'
const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`
const dynamicFallbackInlineCode = `!function(){try{new Function("m","return import(m)")}catch(o){console.warn("vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();`
const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`
const legacyEnvVarMarker = `__VITE_IS_LEGACY__`
/**
* @param {import('.').Options} options
* @returns {import('vite').Plugin[]}
*/
function viteLegacyPlugin(options = {}) {
/**
* @type {import('vite').ResolvedConfig}
*/
let config
const targets = options.targets || 'defaults'
const genLegacy = options.renderLegacyChunks !== false
const genDynamicFallback = genLegacy
const debugFlag = process.env.DEBUG
const isDebug = debugFlag === 'vite:*' || debugFlag === 'vite:legacy'
const facadeToLegacyChunkMap = new Map()
const facadeToLegacyPolyfillMap = new Map()
const facadeToModernPolyfillMap = new Map()
const modernPolyfills = new Set()
// System JS relies on the Promise interface. It needs to be polyfilled for IE 11. (array.iterator is mandatory for supporting Promise.all)
const DEFAULT_LEGACY_POLYFILL = [
'core-js/modules/es.promise',
'core-js/modules/es.array.iterator'
]
const legacyPolyfills = new Set(DEFAULT_LEGACY_POLYFILL)
if (Array.isArray(options.modernPolyfills)) {
options.modernPolyfills.forEach((i) => {
modernPolyfills.add(
i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js`
)
})
}
if (Array.isArray(options.polyfills)) {
options.polyfills.forEach((i) => {
if (i.startsWith(`regenerator`)) {
legacyPolyfills.add(`regenerator-runtime/runtime.js`)
} else {
legacyPolyfills.add(
i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js`
)
}
})
}
if (Array.isArray(options.additionalLegacyPolyfills)) {
options.additionalLegacyPolyfills.forEach((i) => {
legacyPolyfills.add(i)
})
}
/**
* @type {import('vite').Plugin}
*/
const legacyConfigPlugin = {
name: 'vite:legacy-config',
apply: 'build',
config(config) {
if (!config.build) {
config.build = {}
}
if (!config.build.cssTarget) {
// Hint for esbuild that we are targeting legacy browsers when minifying CSS.
// Full CSS compat table available at https://github.com/evanw/esbuild/blob/78e04680228cf989bdd7d471e02bbc2c8d345dc9/internal/compat/css_table.go
// But note that only the `HexRGBA` feature affects the minify outcome.
// HSL & rebeccapurple values will be minified away regardless the target.
// So targeting `chrome61` suffices to fix the compatiblity issue.
config.build.cssTarget = 'chrome61'
}
}
}
/**
* @type {import('vite').Plugin}
*/
const legacyGenerateBundlePlugin = {
name: 'vite:legacy-generate-polyfill-chunk',
apply: 'build',
config() {
return {
build: {
minify: 'terser'
}
}
},
configResolved(config) {
if (!config.build.ssr && genLegacy && config.build.minify === 'esbuild') {
throw new Error(
`Can't use esbuild as the minifier when targeting legacy browsers ` +
`because esbuild minification is not legacy safe.`
)
}
},
async generateBundle(opts, bundle) {
if (config.build.ssr) {
return
}
if (!isLegacyBundle(bundle, opts)) {
if (!modernPolyfills.size) {
return
}
isDebug &&
console.log(
`[@vitejs/plugin-legacy] modern polyfills:`,
modernPolyfills
)
await buildPolyfillChunk(
'polyfills-modern',
modernPolyfills,
bundle,
facadeToModernPolyfillMap,
config.build,
options.externalSystemJS
)
return
}
if (!genLegacy) {
return
}
// legacy bundle
if (legacyPolyfills.size || genDynamicFallback) {
if (!legacyPolyfills.has('es.promise')) {
// check if the target needs Promise polyfill because SystemJS relies
// on it
detectPolyfills(`Promise.resolve()`, targets, legacyPolyfills)
}
isDebug &&
console.log(
`[@vitejs/plugin-legacy] legacy polyfills:`,
legacyPolyfills
)
await buildPolyfillChunk(
'polyfills-legacy',
legacyPolyfills,
bundle,
facadeToLegacyPolyfillMap,
// force using terser for legacy polyfill minification, since esbuild
// isn't legacy-safe
config.build,
options.externalSystemJS
)
}
}
}
/**
* @type {import('vite').Plugin}
*/
const legacyPostPlugin = {
name: 'vite:legacy-post-process',
enforce: 'post',
apply: 'build',
configResolved(_config) {
if (_config.build.lib) {
throw new Error('@vitejs/plugin-legacy does not support library mode.')
}
config = _config
if (!genLegacy || config.build.ssr) {
return
}
/**
* @param {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} fileNames
* @param {string?} defaultFileName
* @returns {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)}
*/
const getLegacyOutputFileName = (
fileNames,
defaultFileName = '[name]-legacy.[hash].js'
) => {
if (!fileNames) {
return path.posix.join(config.build.assetsDir, defaultFileName)
}
return (chunkInfo) => {
let fileName =
typeof fileNames === 'function' ? fileNames(chunkInfo) : fileNames
if (fileName.includes('[name]')) {
// [name]-[hash].[format] -> [name]-legacy-[hash].[format]
fileName = fileName.replace('[name]', '[name]-legacy')
} else {
// entry.js -> entry-legacy.js
fileName = fileName.replace(/(.+)\.(.+)/, '$1-legacy.$2')
}
return fileName
}
}
/**
* @param {import('rollup').OutputOptions} options
* @returns {import('rollup').OutputOptions}
*/
const createLegacyOutput = (options = {}) => {
return {
...options,
format: 'system',
entryFileNames: getLegacyOutputFileName(options.entryFileNames),
chunkFileNames: getLegacyOutputFileName(options.chunkFileNames)
}
}
const { rollupOptions } = config.build
const { output } = rollupOptions
if (Array.isArray(output)) {
rollupOptions.output = [...output.map(createLegacyOutput), ...output]
} else {
rollupOptions.output = [createLegacyOutput(output), output || {}]
}
},
renderChunk(raw, chunk, opts) {
if (config.build.ssr) {
return
}
if (!isLegacyChunk(chunk, opts)) {
if (
options.modernPolyfills &&
!Array.isArray(options.modernPolyfills)
) {
// analyze and record modern polyfills
detectPolyfills(raw, { esmodules: true }, modernPolyfills)
}
const ms = new MagicString(raw)
if (genDynamicFallback && chunk.isEntry) {
ms.prepend(forceDynamicImportUsage)
}
if (raw.includes(legacyEnvVarMarker)) {
const re = new RegExp(legacyEnvVarMarker, 'g')
let match
while ((match = re.exec(raw))) {
ms.overwrite(
match.index,
match.index + legacyEnvVarMarker.length,
`false`
)
}
}
if (config.build.sourcemap) {
return {
code: ms.toString(),
map: ms.generateMap({ hires: true })
}
}
return ms.toString()
}
if (!genLegacy) {
return
}
// @ts-ignore avoid esbuild transform on legacy chunks since it produces
// legacy-unsafe code - e.g. rewriting object properties into shorthands
opts.__vite_skip_esbuild__ = true
const needPolyfills =
options.polyfills !== false && !Array.isArray(options.polyfills)
// transform the legacy chunk with @babel/preset-env
const sourceMaps = !!config.build.sourcemap
const { code, map } = loadBabel().transform(raw, {
babelrc: false,
configFile: false,
compact: true,
sourceMaps,
inputSourceMap: sourceMaps && chunk.map,
presets: [
// forcing our plugin to run before preset-env by wrapping it in a
// preset so we can catch the injected import statements...
[
() => ({
plugins: [
recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
replaceLegacyEnvBabelPlugin(),
wrapIIFEBabelPlugin()
]
})
],
[
'env',
{
targets,
modules: false,
bugfixes: true,
loose: false,
useBuiltIns: needPolyfills ? 'usage' : false,
corejs: needPolyfills
? { version: 3, proposals: false }
: undefined,
shippedProposals: true,
ignoreBrowserslistConfig: options.ignoreBrowserslistConfig
}
]
]
})
return { code, map }
},
transformIndexHtml(html, { chunk }) {
if (config.build.ssr) return
if (!chunk) return
if (chunk.fileName.includes('-legacy')) {
// The legacy bundle is built first, and its index.html isn't actually
// emitted. Here we simply record its corresponding legacy chunk.
facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName)
return
}
/**
* @type {import('vite').HtmlTagDescriptor[]}
*/
const tags = []
const htmlFilename = chunk.facadeModuleId.replace(/\?.*$/, '')
// 1. inject modern polyfills
const modernPolyfillFilename = facadeToModernPolyfillMap.get(
chunk.facadeModuleId
)
if (modernPolyfillFilename) {
tags.push({
tag: 'script',
attrs: {
type: 'module',
src: `${config.base}${modernPolyfillFilename}`
}
})
} else if (modernPolyfills.size) {
throw new Error(
`No corresponding modern polyfill chunk found for ${htmlFilename}`
)
}
if (!genLegacy) {
return { html, tags }
}
// 2. inject Safari 10 nomodule fix
tags.push({
tag: 'script',
attrs: { nomodule: true },
children: safari10NoModuleFix,
injectTo: 'body'
})
// 3. inject legacy polyfills
const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(
chunk.facadeModuleId
)
if (legacyPolyfillFilename) {
tags.push({
tag: 'script',
attrs: {
nomodule: true,
id: legacyPolyfillId,
src: `${config.base}${legacyPolyfillFilename}`
},
injectTo: 'body'
})
} else if (legacyPolyfills.size) {
throw new Error(
`No corresponding legacy polyfill chunk found for ${htmlFilename}`
)
}
// 4. inject legacy entry
const legacyEntryFilename = facadeToLegacyChunkMap.get(
chunk.facadeModuleId
)
if (legacyEntryFilename) {
tags.push({
tag: 'script',
attrs: {
nomodule: true,
// we set the entry path on the element as an attribute so that the
// script content will stay consistent - which allows using a constant
// hash value for CSP.
id: legacyEntryId,
'data-src': config.base + legacyEntryFilename
},
children: systemJSInlineCode,
injectTo: 'body'
})
} else {
throw new Error(
`No corresponding legacy entry chunk found for ${htmlFilename}`
)
}
// 5. inject dynamic import fallback entry
if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {
tags.push({
tag: 'script',
attrs: { type: 'module' },
children: dynamicFallbackInlineCode,
injectTo: 'head'
})
}
return {
html,
tags
}
},
generateBundle(opts, bundle) {
if (config.build.ssr) {
return
}
if (isLegacyBundle(bundle, opts)) {
// avoid emitting duplicate assets
for (const name in bundle) {
if (bundle[name].type === 'asset') {
delete bundle[name]
}
}
}
}
}
let envInjectionFailed = false
/**
* @type {import('vite').Plugin}
*/
const legacyEnvPlugin = {
name: 'vite:legacy-env',
config(config, env) {
if (env) {
return {
define: {
'import.meta.env.LEGACY':
env.command === 'serve' || config.build.ssr
? false
: legacyEnvVarMarker
}
}
} else {
envInjectionFailed = true
}
},
configResolved(config) {
if (envInjectionFailed) {
config.logger.warn(
`[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due ` +
`to incompatible vite version (requires vite@^2.0.0-beta.69).`
)
}
}
}
return [
legacyConfigPlugin,
legacyGenerateBundlePlugin,
legacyPostPlugin,
legacyEnvPlugin
]
}
/**
* @param {string} code
* @param {any} targets
* @param {Set<string>} list
*/
function detectPolyfills(code, targets, list) {
const { ast } = loadBabel().transform(code, {
ast: true,
babelrc: false,
configFile: false,
presets: [
[
'env',
{
targets,
modules: false,
useBuiltIns: 'usage',
corejs: { version: 3, proposals: false },
shippedProposals: true,
ignoreBrowserslistConfig: true
}
]
]
})
for (const node of ast.program.body) {
if (node.type === 'ImportDeclaration') {
const source = node.source.value
if (
source.startsWith('core-js/') ||
source.startsWith('regenerator-runtime/')
) {
list.add(source)
}
}
}
}
/**
* @param {string} name
* @param {Set<string>} imports
* @param {import('rollup').OutputBundle} bundle
* @param {Map<string, string>} facadeToChunkMap
* @param {import('vite').BuildOptions} buildOptions
*/
async function buildPolyfillChunk(
name,
imports,
bundle,
facadeToChunkMap,
buildOptions,
externalSystemJS
) {
let { minify, assetsDir } = buildOptions
minify = minify ? 'terser' : false
const res = await build({
// so that everything is resolved from here
root: __dirname,
configFile: false,
logLevel: 'error',
plugins: [polyfillsPlugin(imports, externalSystemJS)],
build: {
write: false,
target: false,
minify,
assetsDir,
rollupOptions: {
input: {
[name]: polyfillId
},
output: {
format: name.includes('legacy') ? 'iife' : 'es',
manualChunks: undefined
}
}
}
})
const _polyfillChunk = Array.isArray(res) ? res[0] : res
if (!('output' in _polyfillChunk)) return
const polyfillChunk = _polyfillChunk.output[0]
// associate the polyfill chunk to every entry chunk so that we can retrieve
// the polyfill filename in index html transform
for (const key in bundle) {
const chunk = bundle[key]
if (chunk.type === 'chunk' && chunk.facadeModuleId) {
facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName)
}
}
// add the chunk to the bundle
bundle[polyfillChunk.name] = polyfillChunk
}
const polyfillId = '\0vite/legacy-polyfills'
/**
* @param {Set<string>} imports
* @return {import('rollup').Plugin}
*/
function polyfillsPlugin(imports, externalSystemJS) {
return {
name: 'vite:legacy-polyfills',
resolveId(id) {
if (id === polyfillId) {
return id
}
},
load(id) {
if (id === polyfillId) {
return (
[...imports].map((i) => `import "${i}";`).join('') +
(externalSystemJS ? '' : `import "systemjs/dist/s.min.js";`)
)
}
}
}
}
/**
* @param {import('rollup').RenderedChunk} chunk
* @param {import('rollup').NormalizedOutputOptions} options
*/
function isLegacyChunk(chunk, options) {
return options.format === 'system' && chunk.fileName.includes('-legacy')
}
/**
* @param {import('rollup').OutputBundle} bundle
* @param {import('rollup').NormalizedOutputOptions} options
*/
function isLegacyBundle(bundle, options) {
if (options.format === 'system') {
const entryChunk = Object.values(bundle).find(
(output) => output.type === 'chunk' && output.isEntry
)
return !!entryChunk && entryChunk.fileName.includes('-legacy')
}
return false
}
/**
* @param {Set<string>} polyfills
*/
function recordAndRemovePolyfillBabelPlugin(polyfills) {
return ({ types: t }) => ({
name: 'vite-remove-polyfill-import',
post({ path }) {
path.get('body').forEach((p) => {
if (t.isImportDeclaration(p)) {
polyfills.add(p.node.source.value)
p.remove()
}
})
}
})
}
function replaceLegacyEnvBabelPlugin() {
return ({ types: t }) => ({
name: 'vite-replace-env-legacy',
visitor: {
Identifier(path) {
if (path.node.name === legacyEnvVarMarker) {
path.replaceWith(t.booleanLiteral(true))
}
}
}
})
}
function wrapIIFEBabelPlugin() {
return ({ types: t, template }) => {
const buildIIFE = template(';(function(){%%body%%})();')
return {
name: 'vite-wrap-iife',
post({ path }) {
if (!this.isWrapped) {
this.isWrapped = true
path.replaceWith(t.program(buildIIFE({ body: path.node.body })))
}
}
}
}
}
module.exports = viteLegacyPlugin
viteLegacyPlugin.default = viteLegacyPlugin
viteLegacyPlugin.cspHashes = [
createHash('sha256').update(safari10NoModuleFix).digest('base64'),
createHash('sha256').update(systemJSInlineCode).digest('base64'),
createHash('sha256').update(dynamicFallbackInlineCode).digest('base64')
]