Skip to content

Commit

Permalink
fix(css): trim esbuild's minified css (#13893)
Browse files Browse the repository at this point in the history
  • Loading branch information
intrnl authored Aug 16, 2023
1 parent 2c1a45c commit 7682a62
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
20 changes: 15 additions & 5 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
} else {
let content = css
if (config.build.cssMinify) {
content = await minifyCSS(content, config)
content = await minifyCSS(content, config, true)
}
code = `export default ${JSON.stringify(content)}`
}
Expand Down Expand Up @@ -1281,7 +1281,7 @@ async function finalizeCss(
css = await hoistAtRules(css)
}
if (minify && config.build.cssMinify) {
css = await minifyCSS(css, config)
css = await minifyCSS(css, config, false)
}
return css
}
Expand Down Expand Up @@ -1503,7 +1503,15 @@ async function doImportCSSReplace(
return `@import ${wrap}${await replacer(rawUrl)}${wrap}`
}

async function minifyCSS(css: string, config: ResolvedConfig) {
async function minifyCSS(
css: string,
config: ResolvedConfig,
inlined: boolean,
) {
// We want inlined CSS to not end with a linebreak, while ensuring that
// regular CSS assets do end with a linebreak.
// See https://github.com/vitejs/vite/pull/13893#issuecomment-1678628198

if (config.build.cssMinify === 'lightningcss') {
const { code, warnings } = (await importLightningCSS()).transform({
...config.css?.lightningcss,
Expand All @@ -1522,7 +1530,8 @@ async function minifyCSS(css: string, config: ResolvedConfig) {
),
)
}
return code.toString()
// LightningCSS output does not return a linebreak at the end
return code.toString() + (inlined ? '' : '\n')
}
try {
const { code, warnings } = await transform(css, {
Expand All @@ -1536,7 +1545,8 @@ async function minifyCSS(css: string, config: ResolvedConfig) {
colors.yellow(`warnings when minifying css:\n${msgs.join('\n')}`),
)
}
return code
// esbuild output does return a linebreak at the end
return inlined ? code.trimEnd() : code
} catch (e) {
if (e.errors) {
e.message = '[esbuild css minify] ' + e.message
Expand Down
2 changes: 1 addition & 1 deletion playground/glob-import/__tests__/glob-import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const allResult = {
'/dir/baz.json': json,
'/dir/foo.css': isBuild
? {
default: '.foo{color:#00f}\n',
default: '.foo{color:#00f}',
}
: {
default: '.foo {\n color: blue;\n}\n',
Expand Down

0 comments on commit 7682a62

Please sign in to comment.