Skip to content

Commit

Permalink
fix: warn for unresolved css in html (#7911)
Browse files Browse the repository at this point in the history
  • Loading branch information
poyoho committed May 4, 2022
1 parent ba95a2a commit 2b58cb3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
3 changes: 3 additions & 0 deletions packages/playground/html/index.html
Expand Up @@ -5,3 +5,6 @@ <h1>Hello</h1>
<!-- comment two -->
<script type="module"></script>
<script type="module" src="/main.js"></script>
<link rel="icon" href="{{cdn_host}}/cdn/images/favicon.ico" />
<link rel="stylesheet" href="{{cdn_host}}/css.css" type="text/css" />
<script src="{{cdn_host}}/js.js"></script>
29 changes: 27 additions & 2 deletions packages/vite/src/node/plugins/html.ts
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -470,6 +476,25 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
}
}

// 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
Expand Down

0 comments on commit 2b58cb3

Please sign in to comment.