Skip to content

Commit

Permalink
fix(css): inline css module when ssr, minify issue (fix #5471) (#7807)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed May 2, 2022
1 parent b877d30 commit cf8a48a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
10 changes: 9 additions & 1 deletion packages/playground/css/__tests__/css.spec.ts
Expand Up @@ -15,7 +15,11 @@ import {
// in later assertions to ensure CSS HMR doesn't reload the page
test('imported css', async () => {
const css = await page.textContent('.imported-css')
expect(css).toContain('.imported {')
expect(css).toMatch(/\.imported ?{/)
if (isBuild) {
expect(css.trim()).not.toContain('\n') // check minified
}

const glob = await page.textContent('.imported-css-glob')
expect(glob).toContain('.dir-import')
const globEager = await page.textContent('.imported-css-globEager')
Expand Down Expand Up @@ -372,6 +376,10 @@ test('inlined-code', async () => {
// should resolve assets
expect(code).toContain('background:')
expect(code).not.toContain('__VITE_ASSET__')

if (isBuild) {
expect(code.trim()).not.toContain('\n') // check minified
}
})

test('minify css', async () => {
Expand Down
22 changes: 15 additions & 7 deletions packages/vite/src/node/plugins/css.ts
Expand Up @@ -300,11 +300,17 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
return
}

const isHTMLProxy = htmlProxyRE.test(id)
const inlined = inlineRE.test(id)
const modules = cssModulesCache.get(config)!.get(id)
const isHTMLProxy = htmlProxyRE.test(id)

// #6984, #7552
// `foo.module.css` => modulesCode
// `foo.module.css?inline` => cssContent
const modulesCode =
modules && dataToEsm(modules, { namedExports: true, preferConst: true })
modules &&
!inlined &&
dataToEsm(modules, { namedExports: true, preferConst: true })

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

let code: string
if (usedRE.test(id)) {
if (inlined) {
code = `export default ${JSON.stringify(
await minifyCSS(css, config)
)}`
if (modulesCode) {
code = modulesCode
} else {
code = modulesCode || `export default ${JSON.stringify(css)}`
let content = css
if (config.build.minify) {
content = await minifyCSS(content, config)
}
code = `export default ${JSON.stringify(content)}`
}
} else {
code = `export default ''`
Expand Down

0 comments on commit cf8a48a

Please sign in to comment.