Skip to content

Commit

Permalink
fix(css): rewrite url when image-set and url exist at the same time (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
btea authored Dec 4, 2024
1 parent 20fdf21 commit d59efd8
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 10 deletions.
30 changes: 20 additions & 10 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1748,16 +1748,26 @@ const UrlRewritePostcssPlugin: PostCSS.PluginCreator<{
const replacerForDeclaration = (rawUrl: string) => {
return opts.replacer(rawUrl, importer)
}
const rewriterToUse = isCssImageSet
? rewriteCssImageSet
: rewriteCssUrls
promises.push(
rewriterToUse(declaration.value, replacerForDeclaration).then(
(url) => {
declaration.value = url
},
),
)
if (isCssUrl && isCssImageSet) {
promises.push(
rewriteCssUrls(declaration.value, replacerForDeclaration)
.then((url) => rewriteCssImageSet(url, replacerForDeclaration))
.then((url) => {
declaration.value = url
}),
)
} else {
const rewriterToUse = isCssImageSet
? rewriteCssImageSet
: rewriteCssUrls
promises.push(
rewriterToUse(declaration.value, replacerForDeclaration).then(
(url) => {
declaration.value = url
},
),
)
}
}
})
if (promises.length) {
Expand Down
5 changes: 5 additions & 0 deletions playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,11 @@ describe('css url() references', () => {
})
})

test('image-set and url exist at the same time.', async () => {
const imageSet = await getBg('.image-set-and-url-exsiting-at-same-time')
expect(imageSet).toMatch(assetMatch)
})

test('relative in @import', async () => {
expect(await getBg('.css-url-relative-at-imported')).toMatch(assetMatch)
})
Expand Down
12 changes: 12 additions & 0 deletions playground/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,18 @@ <h2>CSS url references</h2>
CSS background image-set() inline style (with multiple descriptor)
</span>
</div>
<div
class="image-set-and-url-exsiting-at-same-time"
style="
background-image: image-set(url('./nested/asset.png')),
url('./nested/asset.png');
background-size: 10px 10px;
"
>
<span style="background: #fff"
>CSS background image-set() and url existing at the same time</span
>
</div>
<div class="css-url-relative-at-imported">
<span style="background: #fff"
>CSS background (relative from @imported file in different dir)</span
Expand Down

0 comments on commit d59efd8

Please sign in to comment.