From d59efd8dfd1c5bf2e7c45c7cdb1c0abc2a05ba02 Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Wed, 4 Dec 2024 16:23:38 +0800 Subject: [PATCH] fix(css): rewrite url when image-set and url exist at the same time (#18868) --- packages/vite/src/node/plugins/css.ts | 30 ++++++++++++++-------- playground/assets/__tests__/assets.spec.ts | 5 ++++ playground/assets/index.html | 12 +++++++++ 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 8615ba0cf89d22..4e7ba788729520 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -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) { diff --git a/playground/assets/__tests__/assets.spec.ts b/playground/assets/__tests__/assets.spec.ts index 3d9b1310370f86..0f33ca7d4b55fb 100644 --- a/playground/assets/__tests__/assets.spec.ts +++ b/playground/assets/__tests__/assets.spec.ts @@ -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) }) diff --git a/playground/assets/index.html b/playground/assets/index.html index b4e71bc85d0897..e41ae78cff0227 100644 --- a/playground/assets/index.html +++ b/playground/assets/index.html @@ -102,6 +102,18 @@

CSS url references

CSS background image-set() inline style (with multiple descriptor) +
+ CSS background image-set() and url existing at the same time +
CSS background (relative from @imported file in different dir)