Skip to content

Commit

Permalink
fix: remove CSS import in CJS correctly in some cases (#18885)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Dec 5, 2024
1 parent d5fb653 commit 690a36f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
17 changes: 16 additions & 1 deletion packages/vite/src/node/__tests__/plugins/css.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,21 +309,36 @@ require("other-module");`

const replacer = getEmptyChunkReplacer(['pure_css_chunk.js'], 'cjs')
const newCode = replacer(code)
expect(newCode.length).toBe(code.length)
expect(newCode).toMatchInlineSnapshot(
`"require("some-module"),/* empty css */require("other-module");"`,
)
// So there should be no pure css chunk anymore
expect(newCode).not.toContain('pure_css_chunk.js')
})

test('replaces require call in minified code that uses comma operator 2', () => {
const code = 'require("pure_css_chunk.js"),console.log();'
const replacer = getEmptyChunkReplacer(['pure_css_chunk.js'], 'cjs')
const newCode = replacer(code)
expect(newCode.length).toBe(code.length)
expect(newCode).toMatchInlineSnapshot(
`"/* empty css */console.log();"`,
)
expect(newCode).not.toContain('pure_css_chunk.js')
})

test('replaces require call in minified code that uses comma operator followed by assignment', () => {
const code =
'require("some-module"),require("pure_css_chunk.js");const v=require("other-module");'

const replacer = getEmptyChunkReplacer(['pure_css_chunk.js'], 'cjs')
expect(replacer(code)).toMatchInlineSnapshot(
const newCode = replacer(code)
expect(newCode.length).toBe(code.length)
expect(newCode).toMatchInlineSnapshot(
`"require("some-module");/* empty css */const v=require("other-module");"`,
)
expect(newCode).not.toContain('pure_css_chunk.js')
})
})

Expand Down
15 changes: 11 additions & 4 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1116,10 +1116,17 @@ export function getEmptyChunkReplacer(
code.replace(
emptyChunkRE,
// remove css import while preserving source map location
(m) =>
outputFormat === 'es'
? `/* empty css ${''.padEnd(m.length - 15)}*/`
: `${m.at(-1)}/* empty css ${''.padEnd(m.length - 16)}*/`,
(m, p1, p2) => {
if (outputFormat === 'es') {
return `/* empty css ${''.padEnd(m.length - 15)}*/`
}
if (p2 === ';') {
// if it ends with `;`, move it before and remove the leading `,`
return `${p2}/* empty css ${''.padEnd(m.length - 16)}*/`
}
// if it ends with `,`, remove it but keep the leading `,` if exists
return `${p1}/* empty css ${''.padEnd(m.length - 15 - p1.length)}*/`
},
)
}

Expand Down

0 comments on commit 690a36f

Please # to comment.