-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
html.ts
1372 lines (1249 loc) · 43.3 KB
/
html.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
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'node:path'
import type {
OutputAsset,
OutputBundle,
OutputChunk,
RollupError,
SourceMapInput,
} from 'rollup'
import MagicString from 'magic-string'
import colors from 'picocolors'
import type { DefaultTreeAdapterMap, ParserError, Token } from 'parse5'
import { stripLiteral } from 'strip-literal'
import type { Plugin } from '../plugin'
import type { ViteDevServer } from '../server'
import {
cleanUrl,
generateCodeFrame,
getHash,
isDataUrl,
isExternalUrl,
normalizePath,
processSrcSet,
removeLeadingSlash,
urlCanParse,
} from '../utils'
import type { ResolvedConfig } from '../config'
import { toOutputFilePathInHtml } from '../build'
import { resolveEnvPrefix } from '../env'
import type { Logger } from '../logger'
import {
assetUrlRE,
checkPublicFile,
getPublicAssetFilename,
publicAssetUrlRE,
urlToBuiltUrl,
} from './asset'
import { isCSSRequest } from './css'
import { modulePreloadPolyfillId } from './modulePreloadPolyfill'
interface ScriptAssetsUrl {
start: number
end: number
url: string
}
const htmlProxyRE =
/\?html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(js|css)$/
const inlineCSSRE = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g
// Do not allow preceding '.', but do allow preceding '...' for spread operations
const inlineImportRE =
/(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/g
const htmlLangRE = /\.(?:html|htm)$/
const importMapRE =
/[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is
const moduleScriptRE =
/[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i
const modulePreloadLinkRE =
/[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i
const importMapAppendRE = new RegExp(
[moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join('|'),
'i',
)
export const isHTMLProxy = (id: string): boolean => htmlProxyRE.test(id)
export const isHTMLRequest = (request: string): boolean =>
htmlLangRE.test(request)
// HTML Proxy Caches are stored by config -> filePath -> index
export const htmlProxyMap = new WeakMap<
ResolvedConfig,
Map<string, Array<{ code: string; map?: SourceMapInput }>>
>()
// HTML Proxy Transform result are stored by config
// `${hash(importer)}_${query.index}` -> transformed css code
// PS: key like `hash(/vite/playground/assets/index.html)_1`)
export const htmlProxyResult = new Map<string, string>()
export function htmlInlineProxyPlugin(config: ResolvedConfig): Plugin {
// Should do this when `constructor` rather than when `buildStart`,
// `buildStart` will be triggered multiple times then the cached result will be emptied.
// https://github.com/vitejs/vite/issues/6372
htmlProxyMap.set(config, new Map())
return {
name: 'vite:html-inline-proxy',
resolveId(id) {
if (htmlProxyRE.test(id)) {
return id
}
},
load(id) {
const proxyMatch = id.match(htmlProxyRE)
if (proxyMatch) {
const index = Number(proxyMatch[1])
const file = cleanUrl(id)
const url = file.replace(normalizePath(config.root), '')
const result = htmlProxyMap.get(config)!.get(url)?.[index]
if (result) {
return result
} else {
throw new Error(`No matching HTML proxy module found from ${id}`)
}
}
},
}
}
export function addToHTMLProxyCache(
config: ResolvedConfig,
filePath: string,
index: number,
result: { code: string; map?: SourceMapInput },
): void {
if (!htmlProxyMap.get(config)) {
htmlProxyMap.set(config, new Map())
}
if (!htmlProxyMap.get(config)!.get(filePath)) {
htmlProxyMap.get(config)!.set(filePath, [])
}
htmlProxyMap.get(config)!.get(filePath)![index] = result
}
export function addToHTMLProxyTransformResult(
hash: string,
code: string,
): void {
htmlProxyResult.set(hash, code)
}
// this extends the config in @vue/compiler-sfc with <link href>
export const assetAttrsConfig: Record<string, string[]> = {
link: ['href'],
video: ['src', 'poster'],
source: ['src', 'srcset'],
img: ['src', 'srcset'],
image: ['xlink:href', 'href'],
use: ['xlink:href', 'href'],
}
export const isAsyncScriptMap = new WeakMap<
ResolvedConfig,
Map<string, boolean>
>()
export function nodeIsElement(
node: DefaultTreeAdapterMap['node'],
): node is DefaultTreeAdapterMap['element'] {
return node.nodeName[0] !== '#'
}
function traverseNodes(
node: DefaultTreeAdapterMap['node'],
visitor: (node: DefaultTreeAdapterMap['node']) => void,
) {
visitor(node)
if (
nodeIsElement(node) ||
node.nodeName === '#document' ||
node.nodeName === '#document-fragment'
) {
node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor))
}
}
export async function traverseHtml(
html: string,
filePath: string,
visitor: (node: DefaultTreeAdapterMap['node']) => void,
): Promise<void> {
// lazy load compiler
const { parse } = await import('parse5')
const ast = parse(html, {
scriptingEnabled: false, // parse inside <noscript>
sourceCodeLocationInfo: true,
onParseError: (e: ParserError) => {
handleParseError(e, html, filePath)
},
})
traverseNodes(ast, visitor)
}
export function getScriptInfo(node: DefaultTreeAdapterMap['element']): {
src: Token.Attribute | undefined
sourceCodeLocation: Token.Location | undefined
isModule: boolean
isAsync: boolean
} {
let src: Token.Attribute | undefined
let sourceCodeLocation: Token.Location | undefined
let isModule = false
let isAsync = false
for (const p of node.attrs) {
if (p.prefix !== undefined) continue
if (p.name === 'src') {
if (!src) {
src = p
sourceCodeLocation = node.sourceCodeLocation?.attrs!['src']
}
} else if (p.name === 'type' && p.value && p.value === 'module') {
isModule = true
} else if (p.name === 'async') {
isAsync = true
}
}
return { src, sourceCodeLocation, isModule, isAsync }
}
const attrValueStartRE = /=\s*(.)/
export function overwriteAttrValue(
s: MagicString,
sourceCodeLocation: Token.Location,
newValue: string,
): MagicString {
const srcString = s.slice(
sourceCodeLocation.startOffset,
sourceCodeLocation.endOffset,
)
const valueStart = srcString.match(attrValueStartRE)
if (!valueStart) {
// overwrite attr value can only be called for a well-defined value
throw new Error(
`[vite:html] internal error, failed to overwrite attribute value`,
)
}
const wrapOffset = valueStart[1] === '"' || valueStart[1] === "'" ? 1 : 0
const valueOffset = valueStart.index! + valueStart[0].length - 1
s.update(
sourceCodeLocation.startOffset + valueOffset + wrapOffset,
sourceCodeLocation.endOffset - wrapOffset,
newValue,
)
return s
}
/**
* Format parse5 @type {ParserError} to @type {RollupError}
*/
function formatParseError(parserError: ParserError, id: string, html: string) {
const formattedError = {
code: parserError.code,
message: `parse5 error code ${parserError.code}`,
frame: generateCodeFrame(
html,
parserError.startOffset,
parserError.endOffset,
),
loc: {
file: id,
line: parserError.startLine,
column: parserError.startCol,
},
} satisfies RollupError
return formattedError
}
function handleParseError(
parserError: ParserError,
html: string,
filePath: string,
) {
switch (parserError.code) {
case 'missing-doctype':
// ignore missing DOCTYPE
return
case 'abandoned-head-element-child':
// Accept elements without closing tag in <head>
return
case 'duplicate-attribute':
// Accept duplicate attributes #9566
// The first attribute is used, browsers silently ignore duplicates
return
case 'non-void-html-element-start-tag-with-trailing-solidus':
// Allow self closing on non-void elements #10439
return
}
const parseError = formatParseError(parserError, filePath, html)
throw new Error(
`Unable to parse HTML; ${parseError.message}\n` +
` at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` +
`${parseError.frame}`,
)
}
/**
* Compiles index.html into an entry js module
*/
export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(
config.plugins,
config.logger,
)
preHooks.unshift(preImportMapHook(config))
preHooks.push(htmlEnvHook(config))
postHooks.push(postImportMapHook())
const processedHtml = new Map<string, string>()
const isExcludedUrl = (url: string) =>
url[0] === '#' || isExternalUrl(url) || isDataUrl(url)
// Same reason with `htmlInlineProxyPlugin`
isAsyncScriptMap.set(config, new Map())
return {
name: 'vite:build-html',
async transform(html, id) {
if (id.endsWith('.html')) {
const relativeUrlPath = path.posix.relative(
config.root,
normalizePath(id),
)
const publicPath = `/${relativeUrlPath}`
const publicBase = getBaseInHTML(relativeUrlPath, config)
const publicToRelative = (filename: string, importer: string) =>
publicBase + filename
const toOutputPublicFilePath = (url: string) =>
toOutputFilePathInHtml(
url.slice(1),
'public',
relativeUrlPath,
'html',
config,
publicToRelative,
)
// Determines true start position for the node, either the < character
// position, or the newline at the end of the previous line's node.
const nodeStartWithLeadingWhitespace = (
node: DefaultTreeAdapterMap['node'],
) => {
if (node.sourceCodeLocation!.startOffset === 0)
return node.sourceCodeLocation!.startOffset
// Gets the offset for the start of the line including the
// newline trailing the previous node
const lineStartOffset =
node.sourceCodeLocation!.startOffset -
node.sourceCodeLocation!.startCol
const line = s.slice(
Math.max(0, lineStartOffset),
node.sourceCodeLocation!.startOffset,
)
// <previous-line-node></previous-line-node>
// <target-node></target-node>
//
// Here we want to target the newline at the end of the previous line
// as the start position for our target.
//
// <previous-node></previous-node>
// <doubled-up-node></doubled-up-node><target-node></target-node>
//
// However, if there is content between our target node start and the
// previous newline, we cannot strip it out without risking content deletion.
return line.trim()
? node.sourceCodeLocation!.startOffset
: lineStartOffset
}
// pre-transform
html = await applyHtmlTransforms(html, preHooks, {
path: publicPath,
filename: id,
})
let js = ''
const s = new MagicString(html)
const scriptUrls: ScriptAssetsUrl[] = []
const styleUrls: ScriptAssetsUrl[] = []
let inlineModuleIndex = -1
let everyScriptIsAsync = true
let someScriptsAreAsync = false
let someScriptsAreDefer = false
const assetUrlsPromises: Promise<void>[] = []
// for each encountered asset url, rewrite original html so that it
// references the post-build location, ignoring empty attributes and
// attributes that directly reference named output.
const namedOutput = Object.keys(
config?.build?.rollupOptions?.input || {},
)
const processAssetUrl = async (url: string) => {
if (
url !== '' && // Empty attribute
!namedOutput.includes(url) && // Direct reference to named output
!namedOutput.includes(removeLeadingSlash(url)) // Allow for absolute references as named output can't be an absolute path
) {
try {
return await urlToBuiltUrl(url, id, config, this)
} catch (e) {
if (e.code !== 'ENOENT') {
throw e
}
}
}
return url
}
await traverseHtml(html, id, (node) => {
if (!nodeIsElement(node)) {
return
}
let shouldRemove = false
// script tags
if (node.nodeName === 'script') {
const { src, sourceCodeLocation, isModule, isAsync } =
getScriptInfo(node)
const url = src && src.value
const isPublicFile = !!(url && checkPublicFile(url, config))
if (isPublicFile) {
// referencing public dir url, prefix with base
overwriteAttrValue(
s,
sourceCodeLocation!,
toOutputPublicFilePath(url),
)
}
if (isModule) {
inlineModuleIndex++
if (url && !isExcludedUrl(url) && !isPublicFile) {
// <script type="module" src="..."/>
// add it as an import
js += `\nimport ${JSON.stringify(url)}`
shouldRemove = true
} else if (node.childNodes.length) {
const scriptNode =
node.childNodes.pop() as DefaultTreeAdapterMap['textNode']
const contents = scriptNode.value
// <script type="module">...</script>
const filePath = id.replace(normalizePath(config.root), '')
addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
code: contents,
})
js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`
shouldRemove = true
}
everyScriptIsAsync &&= isAsync
someScriptsAreAsync ||= isAsync
someScriptsAreDefer ||= !isAsync
} else if (url && !isPublicFile) {
if (!isExcludedUrl(url)) {
config.logger.warn(
`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`,
)
}
} else if (node.childNodes.length) {
const scriptNode =
node.childNodes.pop() as DefaultTreeAdapterMap['textNode']
scriptUrls.push(
...extractImportExpressionFromClassicScript(scriptNode),
)
}
}
// For asset references in index.html, also generate an import
// statement for each - this will be handled by the asset plugin
const assetAttrs = assetAttrsConfig[node.nodeName]
if (assetAttrs) {
for (const p of node.attrs) {
const attrKey = getAttrKey(p)
if (p.value && assetAttrs.includes(attrKey)) {
if (attrKey === 'srcset') {
assetUrlsPromises.push(
(async () => {
const processedUrl = await processSrcSet(
p.value,
async ({ url }) => {
const decodedUrl = decodeURI(url)
if (!isExcludedUrl(decodedUrl)) {
const result = await processAssetUrl(url)
return result !== decodedUrl ? result : url
}
return url
},
)
if (processedUrl !== p.value) {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node, attrKey),
processedUrl,
)
}
})(),
)
} else {
const url = decodeURI(p.value)
if (checkPublicFile(url, config)) {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node, attrKey),
toOutputPublicFilePath(url),
)
} else if (!isExcludedUrl(url)) {
if (
node.nodeName === 'link' &&
isCSSRequest(url) &&
// should not be converted if following attributes are present (#6748)
!node.attrs.some(
(p) =>
p.prefix === undefined &&
(p.name === 'media' || p.name === 'disabled'),
)
) {
// CSS references, convert to import
const importExpression = `\nimport ${JSON.stringify(url)}`
styleUrls.push({
url,
start: nodeStartWithLeadingWhitespace(node),
end: node.sourceCodeLocation!.endOffset,
})
js += importExpression
} else {
assetUrlsPromises.push(
(async () => {
const processedUrl = await processAssetUrl(url)
if (processedUrl !== url) {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node, attrKey),
processedUrl,
)
}
})(),
)
}
}
}
}
}
}
const inlineStyle = findNeedTransformStyleAttribute(node)
if (inlineStyle) {
inlineModuleIndex++
// replace `inline style` with __VITE_INLINE_CSS__**_**__
// and import css in js code
const code = inlineStyle.attr.value
const filePath = id.replace(normalizePath(config.root), '')
addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code })
// will transform with css plugin and cache result with css-post plugin
js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`
const hash = getHash(cleanUrl(id))
// will transform in `applyHtmlTransforms`
overwriteAttrValue(
s,
inlineStyle.location!,
`__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`,
)
}
// <style>...</style>
if (node.nodeName === 'style' && node.childNodes.length) {
const styleNode =
node.childNodes.pop() as DefaultTreeAdapterMap['textNode']
const filePath = id.replace(normalizePath(config.root), '')
inlineModuleIndex++
addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
code: styleNode.value,
})
js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`
const hash = getHash(cleanUrl(id))
// will transform in `applyHtmlTransforms`
s.update(
styleNode.sourceCodeLocation!.startOffset,
styleNode.sourceCodeLocation!.endOffset,
`__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`,
)
}
if (shouldRemove) {
// remove the script tag from the html. we are going to inject new
// ones in the end.
s.remove(
nodeStartWithLeadingWhitespace(node),
node.sourceCodeLocation!.endOffset,
)
}
})
isAsyncScriptMap.get(config)!.set(id, everyScriptIsAsync)
if (someScriptsAreAsync && someScriptsAreDefer) {
config.logger.warn(
`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`,
)
}
await Promise.all(assetUrlsPromises)
// emit <script>import("./aaa")</script> asset
for (const { start, end, url } of scriptUrls) {
if (checkPublicFile(url, config)) {
s.update(start, end, toOutputPublicFilePath(url))
} else if (!isExcludedUrl(url)) {
s.update(start, end, await urlToBuiltUrl(url, id, config, this))
}
}
// ignore <link rel="stylesheet"> if its url can't be resolved
const resolvedStyleUrls = await Promise.all(
styleUrls.map(async (styleUrl) => ({
...styleUrl,
resolved: await this.resolve(styleUrl.url, id),
})),
)
for (const { start, end, url, resolved } of resolvedStyleUrls) {
if (resolved == null) {
config.logger.warnOnce(
`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`,
)
const importExpression = `\nimport ${JSON.stringify(url)}`
js = js.replace(importExpression, '')
} else {
s.remove(start, end)
}
}
processedHtml.set(id, s.toString())
// inject module preload polyfill only when configured and needed
const { modulePreload } = config.build
if (
modulePreload !== false &&
modulePreload.polyfill &&
(someScriptsAreAsync || someScriptsAreDefer)
) {
js = `import "${modulePreloadPolyfillId}";\n${js}`
}
// Force rollup to keep this module from being shared between other entry points.
// If the resulting chunk is empty, it will be removed in generateBundle.
return { code: js, moduleSideEffects: 'no-treeshake' }
}
},
async generateBundle(options, bundle) {
const analyzedChunk: Map<OutputChunk, number> = new Map()
const inlineEntryChunk = new Set<string>()
const getImportedChunks = (
chunk: OutputChunk,
seen: Set<string> = new Set(),
): OutputChunk[] => {
const chunks: OutputChunk[] = []
chunk.imports.forEach((file) => {
const importee = bundle[file]
if (importee?.type === 'chunk' && !seen.has(file)) {
seen.add(file)
// post-order traversal
chunks.push(...getImportedChunks(importee, seen))
chunks.push(importee)
}
})
return chunks
}
const toScriptTag = (
chunk: OutputChunk,
toOutputPath: (filename: string) => string,
isAsync: boolean,
): HtmlTagDescriptor => ({
tag: 'script',
attrs: {
...(isAsync ? { async: true } : {}),
type: 'module',
// crossorigin must be set not only for serving assets in a different origin
// but also to make it possible to preload the script using `<link rel="preload">`.
// `<script type="module">` used to fetch the script with credential mode `omit`,
// however `crossorigin` attribute cannot specify that value.
// https://developer.chrome.com/blog/modulepreload/#ok-so-why-doesnt-link-relpreload-work-for-modules:~:text=For%20%3Cscript%3E,of%20other%20modules.
// Now `<script type="module">` uses `same origin`: https://github.com/whatwg/html/pull/3656#:~:text=Module%20scripts%20are%20always%20fetched%20with%20credentials%20mode%20%22same%2Dorigin%22%20by%20default%20and%20can%20no%20longer%0Ause%20%22omit%22
crossorigin: true,
src: toOutputPath(chunk.fileName),
},
})
const toPreloadTag = (
filename: string,
toOutputPath: (filename: string) => string,
): HtmlTagDescriptor => ({
tag: 'link',
attrs: {
rel: 'modulepreload',
crossorigin: true,
href: toOutputPath(filename),
},
})
const getCssTagsForChunk = (
chunk: OutputChunk,
toOutputPath: (filename: string) => string,
seen: Set<string> = new Set(),
): HtmlTagDescriptor[] => {
const tags: HtmlTagDescriptor[] = []
if (!analyzedChunk.has(chunk)) {
analyzedChunk.set(chunk, 1)
chunk.imports.forEach((file) => {
const importee = bundle[file]
if (importee?.type === 'chunk') {
tags.push(...getCssTagsForChunk(importee, toOutputPath, seen))
}
})
}
chunk.viteMetadata!.importedCss.forEach((file) => {
if (!seen.has(file)) {
seen.add(file)
tags.push({
tag: 'link',
attrs: {
rel: 'stylesheet',
crossorigin: true,
href: toOutputPath(file),
},
})
}
})
return tags
}
for (const [id, html] of processedHtml) {
const relativeUrlPath = path.posix.relative(
config.root,
normalizePath(id),
)
const assetsBase = getBaseInHTML(relativeUrlPath, config)
const toOutputFilePath = (
filename: string,
type: 'asset' | 'public',
) => {
if (isExternalUrl(filename)) {
return filename
} else {
return toOutputFilePathInHtml(
filename,
type,
relativeUrlPath,
'html',
config,
(filename: string, importer: string) => assetsBase + filename,
)
}
}
const toOutputAssetFilePath = (filename: string) =>
toOutputFilePath(filename, 'asset')
const toOutputPublicAssetFilePath = (filename: string) =>
toOutputFilePath(filename, 'public')
const isAsync = isAsyncScriptMap.get(config)!.get(id)!
let result = html
// find corresponding entry chunk
const chunk = Object.values(bundle).find(
(chunk) =>
chunk.type === 'chunk' &&
chunk.isEntry &&
chunk.facadeModuleId === id,
) as OutputChunk | undefined
let canInlineEntry = false
// inject chunk asset links
if (chunk) {
// an entry chunk can be inlined if
// - it's an ES module (e.g. not generated by the legacy plugin)
// - it contains no meaningful code other than import statements
if (options.format === 'es' && isEntirelyImport(chunk.code)) {
canInlineEntry = true
}
// when not inlined, inject <script> for entry and modulepreload its dependencies
// when inlined, discard entry chunk and inject <script> for everything in post-order
const imports = getImportedChunks(chunk)
let assetTags: HtmlTagDescriptor[]
if (canInlineEntry) {
assetTags = imports.map((chunk) =>
toScriptTag(chunk, toOutputAssetFilePath, isAsync),
)
} else {
assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)]
const { modulePreload } = config.build
if (modulePreload !== false) {
const resolveDependencies =
typeof modulePreload === 'object' &&
modulePreload.resolveDependencies
const importsFileNames = imports.map((chunk) => chunk.fileName)
const resolvedDeps = resolveDependencies
? resolveDependencies(chunk.fileName, importsFileNames, {
hostId: relativeUrlPath,
hostType: 'html',
})
: importsFileNames
assetTags.push(
...resolvedDeps.map((i) =>
toPreloadTag(i, toOutputAssetFilePath),
),
)
}
}
assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath))
result = injectToHead(result, assetTags)
}
// inject css link when cssCodeSplit is false
if (!config.build.cssCodeSplit) {
const cssChunk = Object.values(bundle).find(
(chunk) => chunk.type === 'asset' && chunk.name === 'style.css',
) as OutputAsset | undefined
if (cssChunk) {
result = injectToHead(result, [
{
tag: 'link',
attrs: {
rel: 'stylesheet',
crossorigin: true,
href: toOutputAssetFilePath(cssChunk.fileName),
},
},
])
}
}
// no use assets plugin because it will emit file
let match: RegExpExecArray | null
let s: MagicString | undefined
inlineCSSRE.lastIndex = 0
while ((match = inlineCSSRE.exec(result))) {
s ||= new MagicString(result)
const { 0: full, 1: scopedName } = match
const cssTransformedCode = htmlProxyResult.get(scopedName)!
s.update(match.index, match.index + full.length, cssTransformedCode)
}
if (s) {
result = s.toString()
}
result = await applyHtmlTransforms(
result,
[...normalHooks, ...postHooks],
{
path: '/' + relativeUrlPath,
filename: id,
bundle,
chunk,
},
)
// resolve asset url references
result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
const file = this.getFileName(fileHash)
if (chunk) {
chunk.viteMetadata!.importedAssets.add(cleanUrl(file))
}
return toOutputAssetFilePath(file) + postfix
})
result = result.replace(publicAssetUrlRE, (_, fileHash) => {
const publicAssetPath = toOutputPublicAssetFilePath(
getPublicAssetFilename(fileHash, config)!,
)
return urlCanParse(publicAssetPath)
? publicAssetPath
: normalizePath(publicAssetPath)
})
if (chunk && canInlineEntry) {
inlineEntryChunk.add(chunk.fileName)
}
const shortEmitName = normalizePath(path.relative(config.root, id))
this.emitFile({
type: 'asset',
fileName: shortEmitName,
source: result,
})
}
for (const fileName of inlineEntryChunk) {
// all imports from entry have been inlined to html, prevent rollup from outputting it
delete bundle[fileName]
}
},
}
}
// <tag style="... url(...) or image-set(...) ..."></tag>
// extract inline styles as virtual css
export function findNeedTransformStyleAttribute(
node: DefaultTreeAdapterMap['element'],
): { attr: Token.Attribute; location?: Token.Location } | undefined {
const attr = node.attrs.find(
(prop) =>
prop.prefix === undefined &&
prop.name === 'style' &&
// only url(...) or image-set(...) in css need to emit file
(prop.value.includes('url(') || prop.value.includes('image-set(')),
)
if (!attr) return undefined
const location = node.sourceCodeLocation?.attrs?.['style']
return { attr, location }
}
export function extractImportExpressionFromClassicScript(
scriptTextNode: DefaultTreeAdapterMap['textNode'],
): ScriptAssetsUrl[] {
const startOffset = scriptTextNode.sourceCodeLocation!.startOffset
const cleanCode = stripLiteral(scriptTextNode.value)
const scriptUrls: ScriptAssetsUrl[] = []
let match: RegExpExecArray | null
inlineImportRE.lastIndex = 0
while ((match = inlineImportRE.exec(cleanCode))) {
const { 1: url, index } = match
const startUrl = cleanCode.indexOf(url, index)
const start = startUrl + 1
const end = start + url.length - 2
scriptUrls.push({
start: start + startOffset,
end: end + startOffset,
url: scriptTextNode.value.slice(start, end),
})
}
return scriptUrls
}
export interface HtmlTagDescriptor {
tag: string
attrs?: Record<string, string | boolean | undefined>
children?: string | HtmlTagDescriptor[]
/**
* default: 'head-prepend'
*/
injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend'
}
export type IndexHtmlTransformResult =
| string
| HtmlTagDescriptor[]
| {
html: string
tags: HtmlTagDescriptor[]
}
export interface IndexHtmlTransformContext {
/**
* public path when served
*/
path: string
/**
* filename on disk
*/
filename: string
server?: ViteDevServer
bundle?: OutputBundle
chunk?: OutputChunk
originalUrl?: string
}
export type IndexHtmlTransformHook = (
this: void,
html: string,
ctx: IndexHtmlTransformContext,
) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>
export type IndexHtmlTransform =
| IndexHtmlTransformHook
| {
order?: 'pre' | 'post' | null
/**
* @deprecated renamed to `order`
*/
enforce?: 'pre' | 'post'
/**
* @deprecated renamed to `handler`
*/
transform: IndexHtmlTransformHook
}
| {
order?: 'pre' | 'post' | null
/**
* @deprecated renamed to `order`
*/
enforce?: 'pre' | 'post'
handler: IndexHtmlTransformHook