From 2b58cb3faaa8f0da983888d0bd1f0f2a3a34de56 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 5 May 2022 02:45:48 +0800 Subject: [PATCH] fix: warn for unresolved css in html (#7911) --- packages/playground/html/index.html | 3 +++ packages/vite/src/node/plugins/html.ts | 29 ++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/packages/playground/html/index.html b/packages/playground/html/index.html index 7320ff2b097db0..783cad93172f7a 100644 --- a/packages/playground/html/index.html +++ b/packages/playground/html/index.html @@ -5,3 +5,6 @@

Hello

+ + + diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index bf3d662066630b..0223c351af6071 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -247,6 +247,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { const s = new MagicString(html) const assetUrls: AttributeNode[] = [] const scriptUrls: ScriptAssetsUrl[] = [] + const styleUrls: ScriptAssetsUrl[] = [] let inlineModuleIndex = -1 let everyScriptIsAsync = true @@ -339,8 +340,13 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { if (!isExcludedUrl(url)) { if (node.tag === 'link' && isCSSRequest(url)) { // CSS references, convert to import - js += `\nimport ${JSON.stringify(url)}` - shouldRemove = true + const importExpression = `\nimport ${JSON.stringify(url)}` + styleUrls.push({ + url, + start: node.loc.start.offset, + end: node.loc.end.offset + }) + js += importExpression } else { assetUrls.push(p) } @@ -470,6 +476,25 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { } } + // ignore 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