Skip to content

Commit 690a36f

Browse files
authored
fix: remove CSS import in CJS correctly in some cases (#18885)
1 parent d5fb653 commit 690a36f

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

packages/vite/src/node/__tests__/plugins/css.spec.ts

+16-1
Original file line numberDiff line numberDiff line change
@@ -309,21 +309,36 @@ require("other-module");`
309309

310310
const replacer = getEmptyChunkReplacer(['pure_css_chunk.js'], 'cjs')
311311
const newCode = replacer(code)
312+
expect(newCode.length).toBe(code.length)
312313
expect(newCode).toMatchInlineSnapshot(
313314
`"require("some-module"),/* empty css */require("other-module");"`,
314315
)
315316
// So there should be no pure css chunk anymore
316317
expect(newCode).not.toContain('pure_css_chunk.js')
317318
})
318319

320+
test('replaces require call in minified code that uses comma operator 2', () => {
321+
const code = 'require("pure_css_chunk.js"),console.log();'
322+
const replacer = getEmptyChunkReplacer(['pure_css_chunk.js'], 'cjs')
323+
const newCode = replacer(code)
324+
expect(newCode.length).toBe(code.length)
325+
expect(newCode).toMatchInlineSnapshot(
326+
`"/* empty css */console.log();"`,
327+
)
328+
expect(newCode).not.toContain('pure_css_chunk.js')
329+
})
330+
319331
test('replaces require call in minified code that uses comma operator followed by assignment', () => {
320332
const code =
321333
'require("some-module"),require("pure_css_chunk.js");const v=require("other-module");'
322334

323335
const replacer = getEmptyChunkReplacer(['pure_css_chunk.js'], 'cjs')
324-
expect(replacer(code)).toMatchInlineSnapshot(
336+
const newCode = replacer(code)
337+
expect(newCode.length).toBe(code.length)
338+
expect(newCode).toMatchInlineSnapshot(
325339
`"require("some-module");/* empty css */const v=require("other-module");"`,
326340
)
341+
expect(newCode).not.toContain('pure_css_chunk.js')
327342
})
328343
})
329344

packages/vite/src/node/plugins/css.ts

+11-4
Original file line numberDiff line numberDiff line change
@@ -1116,10 +1116,17 @@ export function getEmptyChunkReplacer(
11161116
code.replace(
11171117
emptyChunkRE,
11181118
// remove css import while preserving source map location
1119-
(m) =>
1120-
outputFormat === 'es'
1121-
? `/* empty css ${''.padEnd(m.length - 15)}*/`
1122-
: `${m.at(-1)}/* empty css ${''.padEnd(m.length - 16)}*/`,
1119+
(m, p1, p2) => {
1120+
if (outputFormat === 'es') {
1121+
return `/* empty css ${''.padEnd(m.length - 15)}*/`
1122+
}
1123+
if (p2 === ';') {
1124+
// if it ends with `;`, move it before and remove the leading `,`
1125+
return `${p2}/* empty css ${''.padEnd(m.length - 16)}*/`
1126+
}
1127+
// if it ends with `,`, remove it but keep the leading `,` if exists
1128+
return `${p1}/* empty css ${''.padEnd(m.length - 15 - p1.length)}*/`
1129+
},
11231130
)
11241131
}
11251132

0 commit comments

Comments
 (0)