Skip to content

Commit

Permalink
fix(css): ensure code is valid after empty css chunk imports are removed
Browse files Browse the repository at this point in the history
Make sure that minified code that chains `require` calls with the `,` operator will not result in invalid code when removing
one of the chained requires. Previously the last require that terminates with a semicolon was removed with the semicolon.
This produced invalid code like `require(), /* empty css */const foo =`

Now we append either a comma if a next require call was chained, like
`require(...), require(css), other` --> `require(...)/* empty css */, other`

Or terminate with a semicolon
`require(...), require(css); const foo = ...` --> `require(...)/* empty css */; const foo = ...`

Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
  • Loading branch information
susnux committed Oct 2, 2023
1 parent a30fdd9 commit 3842602
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -739,10 +739,13 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
.map((file) => path.basename(file))
.join('|')
.replace(/\./g, '\\.')
// require and import calls might be chained by minifier using the comma operator
// in this case we have to keep one comma
// if a next require is chained or add a semicolon to terminate the chain.
const emptyChunkRE = new RegExp(
opts.format === 'es'
? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];\n?`
: `\\brequire\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\);\n?`,
? `(\\b|,\\s*)import\\s*["'][^"']*(?:${emptyChunkFiles})["'](;|,)`
: `(\\b|,\\s*)require\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\)(;|,)`,
'g',
)
for (const file in bundle) {
Expand All @@ -769,7 +772,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
chunk.code = chunk.code.replace(
emptyChunkRE,
// remove css import while preserving source map location
(m) => `/* empty css ${''.padEnd(m.length - 15)}*/`,
(m) => `/* empty css ${''.padEnd(m.length - 16)}*/${m.at(-1)}`,
)
}
}
Expand Down

0 comments on commit 3842602

Please sign in to comment.