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

feat(css): shrink base64 usage in css file #12517

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 56 additions & 6 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ const postcssConfigCache = new WeakMap<
PostCSSConfigResult | null | Promise<PostCSSConfigResult | null>
>()

const rootCssVariableCache = new WeakMap<ResolvedConfig, Map<string, string>>()

function encodePublicUrlsInCSS(config: ResolvedConfig) {
return config.command === 'build'
}
Expand All @@ -182,6 +184,7 @@ function encodePublicUrlsInCSS(config: ResolvedConfig) {
export function cssPlugin(config: ResolvedConfig): Plugin {
let server: ViteDevServer
let moduleCache: Map<string, Record<string, string>>
let rootVarsCache: Map<string, string>

const resolveUrl = config.createResolver({
preferRelative: true,
Expand All @@ -204,6 +207,9 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
moduleCache = new Map<string, Record<string, string>>()
cssModulesCache.set(config, moduleCache)

rootVarsCache = new Map<string, string>()
rootCssVariableCache.set(config, rootVarsCache)

removedPureCssFilesCache.set(config, new Map<string, RenderedChunk>())
},

Expand Down Expand Up @@ -243,7 +249,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
modules,
deps,
map,
} = await compileCSS(id, raw, config, urlReplacer)
} = await compileCSS(id, raw, config, { urlReplacer, rootVarsCache })
if (modules) {
moduleCache.set(id, modules)
}
Expand Down Expand Up @@ -491,6 +497,18 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
return null
}

// remove duplicate base64 css variables
const base64VarRE = /(--base64-[^:]+):.+?\);/g
const cssVarCache = new Map<string, boolean>()
chunkCSS = chunkCSS.replace(base64VarRE, (s, cssVar) => {
if (cssVarCache.has(cssVar)) {
return ''
}

cssVarCache.set(cssVar, true)
return s
})

const publicAssetUrlMap = publicAssetUrlCache.get(config)!

// resolve asset URL placeholders to their built file URLs
Expand Down Expand Up @@ -809,7 +827,10 @@ async function compileCSS(
id: string,
code: string,
config: ResolvedConfig,
urlReplacer?: CssUrlReplacer,
options?: {
urlReplacer?: CssUrlReplacer
rootVarsCache: Map<string, string>
},
): Promise<{
code: string
map?: SourceMapInput
Expand Down Expand Up @@ -938,11 +959,12 @@ async function compileCSS(
)
}

if (urlReplacer) {
if (options?.urlReplacer) {
postcssPlugins.push(
UrlRewritePostcssPlugin({
replacer: urlReplacer,
replacer: options.urlReplacer,
logger: config.logger,
rootVars: options.rootVarsCache,
}),
)
}
Expand Down Expand Up @@ -1236,6 +1258,7 @@ const cssImageSetRE = /(?<=image-set\()((?:[\w\-]{1,256}\([^)]*\)|[^)])*)(?=\))/
const UrlRewritePostcssPlugin: PostCSS.PluginCreator<{
replacer: CssUrlReplacer
logger: Logger
rootVars: Map<string, string>
}> = (opts) => {
if (!opts) {
throw new Error('base or replace is required')
Expand All @@ -1245,6 +1268,7 @@ const UrlRewritePostcssPlugin: PostCSS.PluginCreator<{
postcssPlugin: 'vite-url-rewrite',
Once(root) {
const promises: Promise<void>[] = []
const isCssFile = !root.source?.input.file?.includes('.html')
root.walkDecls((declaration) => {
const importer = declaration.source?.input.file
if (!importer) {
Expand All @@ -1267,14 +1291,40 @@ const UrlRewritePostcssPlugin: PostCSS.PluginCreator<{
promises.push(
rewriterToUse(declaration.value, replacerForDeclaration).then(
(url) => {
declaration.value = url
let match

if (
isCssFile &&
(match = url.match(/url\(['"]?data:.+?;base64,.+?\)/))
) {
const [base64] = match

sun0day marked this conversation as resolved.
Show resolved Hide resolved
const cssVar =
opts.rootVars.get(base64) || `--base64-${getHash(base64)}`
opts.rootVars.set(base64, cssVar)

declaration.value = url.replace(base64, `var(${cssVar})`)
} else {
declaration.value = url
}
},
),
)
}
})
if (promises.length) {
return Promise.all(promises) as any
return Promise.all(promises).then(() => {
isCssFile &&
root.prepend(
`:root{${Array.from(opts.rootVars.entries()).reduce(
(cssVars, [url, cssVar]) => {
cssVars += `\n${cssVar}: ${url};`
return cssVars
},
'',
)}}`,
)
}) as any
}
},
}
Expand Down