Skip to content

Commit

Permalink
fix: lightningCSS should load external URL in CSS file (#13692)
Browse files Browse the repository at this point in the history
Co-authored-by: Arnaud Barré <arnaud.barre@carbometrix.com>
  • Loading branch information
Marabyte and ArnaudBarre committed Jul 3, 2023
1 parent 277e844 commit 8517645
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 6 deletions.
19 changes: 13 additions & 6 deletions packages/vite/src/node/plugins/css.ts
Expand Up @@ -1420,6 +1420,14 @@ async function rewriteCssImageSet(
return url
})
}
function skipUrlReplacer(rawUrl: string) {
return (
isExternalUrl(rawUrl) ||
isDataUrl(rawUrl) ||
rawUrl[0] === '#' ||
varRE.test(rawUrl)
)
}
async function doUrlReplace(
rawUrl: string,
matched: string,
Expand All @@ -1433,12 +1441,7 @@ async function doUrlReplace(
rawUrl = rawUrl.slice(1, -1)
}

if (
isExternalUrl(rawUrl) ||
isDataUrl(rawUrl) ||
rawUrl[0] === '#' ||
varRE.test(rawUrl)
) {
if (skipUrlReplacer(rawUrl)) {
return matched
}

Expand Down Expand Up @@ -2184,6 +2187,10 @@ async function compileLightningCSS(
for (const dep of res.dependencies!) {
switch (dep.type) {
case 'url':
if (skipUrlReplacer(dep.url)) {
css = css.replace(dep.placeholder, dep.url)
break
}
deps.add(dep.url)
if (urlReplacer) {
css = css.replace(dep.placeholder, await urlReplacer(dep.url, id))
Expand Down
6 changes: 6 additions & 0 deletions playground/css-lightningcss/__tests__/lightningcss.spec.ts
Expand Up @@ -2,6 +2,7 @@ import { expect, test } from 'vitest'
import {
editFile,
findAssetFile,
getBg,
getColor,
isBuild,
page,
Expand Down Expand Up @@ -65,3 +66,8 @@ test.runIf(isBuild)('minify css', async () => {
expect(cssFile).toMatch('rgba(')
expect(cssFile).not.toMatch('#ffff00b3')
})

test('css with external url', async () => {
const css = await page.$('.external')
expect(await getBg(css)).toMatch('url("https://vitejs.dev/logo.svg")')
})
7 changes: 7 additions & 0 deletions playground/css-lightningcss/external-url.css
@@ -0,0 +1,7 @@
.external {
background-image: url('https://vitejs.dev/logo.svg');
background-size: 100%;
width: 200px;
height: 200px;
background-color: #bed;
}
3 changes: 3 additions & 0 deletions playground/css-lightningcss/index.html
Expand Up @@ -23,6 +23,9 @@ <h1>Lightning CSS</h1>

<p>Inline CSS module:</p>
<pre class="modules-inline"></pre>

<p>External URL</p>
<div class="external"></div>
</div>

<script type="module" src="./main.js"></script>
1 change: 1 addition & 0 deletions playground/css-lightningcss/main.js
@@ -1,6 +1,7 @@
import './minify.css'
import './imported.css'
import mod from './mod.module.css'
import './external-url.css'

document.querySelector('.modules').classList.add(mod['apply-color'])
text('.modules-code', JSON.stringify(mod, null, 2))
Expand Down

0 comments on commit 8517645

Please sign in to comment.