Skip to content

Commit

Permalink
feat: use lightningcss by default for cssMinify (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Dec 3, 2024
1 parent 4e75b7f commit d437a93
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 54 deletions.
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
"dependencies": {
"esbuild": "^0.24.0",
"lightningcss": "^1.28.1",
"postcss": "^8.4.49",
"rolldown": "0.14.0-snapshot-1cfa47c-20241129015040",
"rollup": "^4.23.0"
Expand Down Expand Up @@ -123,7 +124,6 @@
"etag": "^1.8.1",
"http-proxy": "^1.18.1",
"launch-editor-middleware": "^2.9.1",
"lightningcss": "^1.28.1",
"magic-string": "^0.30.13",
"mlly": "^1.7.3",
"mrmime": "^2.0.0",
Expand Down
5 changes: 3 additions & 2 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export interface BuildEnvironmentOptions {
/**
* Override CSS minification specifically instead of defaulting to `build.minify`,
* so you can configure minification for JS and CSS separately.
* @default 'esbuild'
* @default 'lightningcss'
*/
cssMinify?: boolean | 'esbuild' | 'lightningcss'
/**
Expand Down Expand Up @@ -449,7 +449,8 @@ export function resolveBuildEnvironmentOptions(
...merged,
cssTarget: merged.cssTarget ?? merged.target,
cssMinify:
merged.cssMinify ?? (consumer === 'server' ? 'esbuild' : !!merged.minify),
merged.cssMinify ??
(consumer === 'server' ? 'lightningcss' : !!merged.minify),
// Resolve to false | object
modulePreload:
merged.modulePreload === false
Expand Down
99 changes: 51 additions & 48 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import type Less from 'less'
import type { Alias } from 'dep-types/alias'
import type { LightningCSSOptions } from 'types/internal/lightningcssOptions'
import type { TransformOptions } from 'esbuild'
import { formatMessages, transform } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
import { WorkerWithFallback } from 'artichokie'
import { globSync } from 'tinyglobby'
Expand Down Expand Up @@ -1932,56 +1931,58 @@ async function minifyCSS(
// 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,
targets: convertTargets(config.build.cssTarget),
cssModules: undefined,
// TODO: Pass actual filename here, which can also be passed to esbuild's
// `sourcefile` option below to improve error messages
filename: defaultCssBundleName,
code: Buffer.from(css),
minify: true,
})
if (warnings.length) {
config.logger.warn(
colors.yellow(
`warnings when minifying css:\n${warnings
.map((w) => w.message)
.join('\n')}`,
),
)
if (config.build.cssMinify === 'esbuild') {
const { transform, formatMessages } = await importEsbuild()
try {
const { code, warnings } = await transform(css, {
loader: 'css',
target: config.build.cssTarget || undefined,
...resolveMinifyCssEsbuildOptions(config.esbuild || {}),
})
if (warnings.length) {
const msgs = await formatMessages(warnings, { kind: 'warning' })
config.logger.warn(
colors.yellow(`warnings when minifying css:\n${msgs.join('\n')}`),
)
}
// 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
const msgs = await formatMessages(e.errors, { kind: 'error' })
e.frame = '\n' + msgs.join('\n')
e.loc = e.errors[0].location
}
throw e
}

// NodeJS res.code = Buffer
// Deno res.code = Uint8Array
// For correct decode compiled css need to use TextDecoder
// LightningCSS output does not return a linebreak at the end
return decoder.decode(code) + (inlined ? '' : '\n')
}
try {
const { code, warnings } = await transform(css, {
loader: 'css',
target: config.build.cssTarget || undefined,
...resolveMinifyCssEsbuildOptions(config.esbuild || {}),
})
if (warnings.length) {
const msgs = await formatMessages(warnings, { kind: 'warning' })
config.logger.warn(
colors.yellow(`warnings when minifying css:\n${msgs.join('\n')}`),
)
}
// 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
const msgs = await formatMessages(e.errors, { kind: 'error' })
e.frame = '\n' + msgs.join('\n')
e.loc = e.errors[0].location
}
throw e

const { code, warnings } = (await importLightningCSS()).transform({
...config.css?.lightningcss,
targets: convertTargets(config.build.cssTarget),
cssModules: undefined,
// TODO: Pass actual filename here, which can also be passed to esbuild's
// `sourcefile` option below to improve error messages
filename: defaultCssBundleName,
code: Buffer.from(css),
minify: true,
})
if (warnings.length) {
config.logger.warn(
colors.yellow(
`warnings when minifying css:\n${warnings
.map((w) => w.message)
.join('\n')}`,
),
)
}

// NodeJS res.code = Buffer
// Deno res.code = Uint8Array
// For correct decode compiled css need to use TextDecoder
// LightningCSS output does not return a linebreak at the end
return decoder.decode(code) + (inlined ? '' : '\n')
}

function resolveMinifyCssEsbuildOptions(
Expand Down Expand Up @@ -3149,6 +3150,8 @@ function isPreProcessor(lang: any): lang is PreprocessLang {
return lang && preprocessorSet.has(lang)
}

const importEsbuild = createCachedImport(() => import('esbuild'))

const importLightningCSS = createCachedImport(() => import('lightningcss'))
async function compileLightningCSS(
id: string,
Expand Down
3 changes: 3 additions & 0 deletions playground/minify/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@ export default defineConfig({
legalComments: 'none',
minifySyntax: false,
},
build: {
cssMinify: 'esbuild',
},
})
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit d437a93

Please sign in to comment.