Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(css): inline css module when ssr, minify issue (fix #5471) #7807

Merged
merged 2 commits into from May 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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