Skip to content

Commit cf8a48a

Browse files
authored
fix(css): inline css module when ssr, minify issue (fix #5471) (#7807)
1 parent b877d30 commit cf8a48a

2 files changed

Lines changed: 24 additions & 8 deletions

File tree

packages/playground/css/__tests__/css.spec.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ import {
1515
// in later assertions to ensure CSS HMR doesn't reload the page
1616
test('imported css', async () => {
1717
const css = await page.textContent('.imported-css')
18-
expect(css).toContain('.imported {')
18+
expect(css).toMatch(/\.imported ?{/)
19+
if (isBuild) {
20+
expect(css.trim()).not.toContain('\n') // check minified
21+
}
22+
1923
const glob = await page.textContent('.imported-css-glob')
2024
expect(glob).toContain('.dir-import')
2125
const globEager = await page.textContent('.imported-css-globEager')
@@ -372,6 +376,10 @@ test('inlined-code', async () => {
372376
// should resolve assets
373377
expect(code).toContain('background:')
374378
expect(code).not.toContain('__VITE_ASSET__')
379+
380+
if (isBuild) {
381+
expect(code.trim()).not.toContain('\n') // check minified
382+
}
375383
})
376384

377385
test('minify css', async () => {

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

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -300,11 +300,17 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
300300
return
301301
}
302302

303+
const isHTMLProxy = htmlProxyRE.test(id)
303304
const inlined = inlineRE.test(id)
304305
const modules = cssModulesCache.get(config)!.get(id)
305-
const isHTMLProxy = htmlProxyRE.test(id)
306+
307+
// #6984, #7552
308+
// `foo.module.css` => modulesCode
309+
// `foo.module.css?inline` => cssContent
306310
const modulesCode =
307-
modules && dataToEsm(modules, { namedExports: true, preferConst: true })
311+
modules &&
312+
!inlined &&
313+
dataToEsm(modules, { namedExports: true, preferConst: true })
308314

309315
if (config.command === 'serve') {
310316
if (isDirectCSSRequest(id)) {
@@ -366,12 +372,14 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
366372

367373
let code: string
368374
if (usedRE.test(id)) {
369-
if (inlined) {
370-
code = `export default ${JSON.stringify(
371-
await minifyCSS(css, config)
372-
)}`
375+
if (modulesCode) {
376+
code = modulesCode
373377
} else {
374-
code = modulesCode || `export default ${JSON.stringify(css)}`
378+
let content = css
379+
if (config.build.minify) {
380+
content = await minifyCSS(content, config)
381+
}
382+
code = `export default ${JSON.stringify(content)}`
375383
}
376384
} else {
377385
code = `export default ''`

0 commit comments

Comments
 (0)