From daeaf2ada3832491e6400cf3e823b40b839ffc7d Mon Sep 17 00:00:00 2001 From: bluwy Date: Fri, 31 May 2024 22:01:35 +0800 Subject: [PATCH 1/2] fix(css): handle url replacing when preprocessing with lightningcss --- packages/vite/src/node/plugins/css.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index e4b08ba4b8e22b..ecdc19a5bbd8d8 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -2780,6 +2780,8 @@ async function compileLightningCSS( if (urlReplacer) { const replaceUrl = await urlReplacer(dep.url, id) css = css.replace(dep.placeholder, () => replaceUrl) + } else { + css = css.replace(dep.placeholder, () => dep.url) } break default: From e457aa1ec1ae53a49194dcc3126fee8b854e6861 Mon Sep 17 00:00:00 2001 From: bluwy Date: Fri, 31 May 2024 22:27:39 +0800 Subject: [PATCH 2/2] chore: add test --- .../src/node/__tests__/plugins/css.spec.ts | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index cfd7dc6e6d4e47..e1c435211c9593 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -9,6 +9,7 @@ import { cssUrlRE, getEmptyChunkReplacer, hoistAtRules, + preprocessCSS, } from '../../plugins/css' describe('search css url function', () => { @@ -65,6 +66,7 @@ background: #f0f; }`, }, { + configFile: false, resolve: { alias: [ { @@ -101,6 +103,7 @@ position: fixed; test('custom generateScopedName', async () => { const { transform, resetMock } = await createCssPluginTransform(undefined, { + configFile: false, css: { modules: { generateScopedName: 'custom__[hash:base64:5]', @@ -338,3 +341,50 @@ require("other-module");` ) }) }) + +describe('preprocessCSS', () => { + test('works', async () => { + const resolvedConfig = await resolveConfig({ configFile: false }, 'serve') + const result = await preprocessCSS( + `\ +.foo { + color:red; + background: url(./foo.png); +}`, + 'foo.css', + resolvedConfig, + ) + expect(result.code).toMatchInlineSnapshot(` + ".foo { + color:red; + background: url(./foo.png); + }" + `) + }) + + test('works with lightningcss', async () => { + const resolvedConfig = await resolveConfig( + { + configFile: false, + css: { transformer: 'lightningcss' }, + }, + 'serve', + ) + const result = await preprocessCSS( + `\ +.foo { + color: red; + background: url(./foo.png); +}`, + 'foo.css', + resolvedConfig, + ) + expect(result.code).toMatchInlineSnapshot(` + ".foo { + color: red; + background: url("./foo.png"); + } + " + `) + }) +})