From 6fbb5e0a036faa835f4154ae0489db4c9b47c44c Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Mon, 3 Jun 2024 14:27:39 +0800 Subject: [PATCH] fix(css): handle url replacing when preprocessing with lightningcss (#17364) --- .../src/node/__tests__/plugins/css.spec.ts | 50 +++++++++++++++++++ packages/vite/src/node/plugins/css.ts | 2 + 2 files changed, 52 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"); + } + " + `) + }) +}) 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: