Skip to content

Commit 2b58cb3

Browse files
authored
fix: warn for unresolved css in html (#7911)
1 parent ba95a2a commit 2b58cb3

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

packages/playground/html/index.html

+3
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,6 @@ <h1>Hello</h1>
55
<!-- comment two -->
66
<script type="module"></script>
77
<script type="module" src="/main.js"></script>
8+
<link rel="icon" href="{{cdn_host}}/cdn/images/favicon.ico" />
9+
<link rel="stylesheet" href="{{cdn_host}}/css.css" type="text/css" />
10+
<script src="{{cdn_host}}/js.js"></script>

packages/vite/src/node/plugins/html.ts

+27-2
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
247247
const s = new MagicString(html)
248248
const assetUrls: AttributeNode[] = []
249249
const scriptUrls: ScriptAssetsUrl[] = []
250+
const styleUrls: ScriptAssetsUrl[] = []
250251
let inlineModuleIndex = -1
251252

252253
let everyScriptIsAsync = true
@@ -339,8 +340,13 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
339340
if (!isExcludedUrl(url)) {
340341
if (node.tag === 'link' && isCSSRequest(url)) {
341342
// CSS references, convert to import
342-
js += `\nimport ${JSON.stringify(url)}`
343-
shouldRemove = true
343+
const importExpression = `\nimport ${JSON.stringify(url)}`
344+
styleUrls.push({
345+
url,
346+
start: node.loc.start.offset,
347+
end: node.loc.end.offset
348+
})
349+
js += importExpression
344350
} else {
345351
assetUrls.push(p)
346352
}
@@ -470,6 +476,25 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
470476
}
471477
}
472478

479+
// ignore <link rel="stylesheet"> if its url can't be resolved
480+
const resolvedStyleUrls = await Promise.all(
481+
styleUrls.map(async (styleUrl) => ({
482+
...styleUrl,
483+
resolved: await this.resolve(styleUrl.url, id)
484+
}))
485+
)
486+
for (const { start, end, url, resolved } of resolvedStyleUrls) {
487+
if (resolved == null) {
488+
config.logger.warnOnce(
489+
`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`
490+
)
491+
const importExpression = `\nimport ${JSON.stringify(url)}`
492+
js = js.replace(importExpression, '')
493+
} else {
494+
s.remove(start, end)
495+
}
496+
}
497+
473498
processedHtml.set(id, s.toString())
474499

475500
// inject module preload polyfill only when configured and needed

0 commit comments

Comments
 (0)