From 963614bff7039207c0b2d9e8c2c5780b74ee176a Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 22 Nov 2020 10:50:32 -0500 Subject: [PATCH] perf: remove empty chunk from css extraction --- src/node/build/buildPluginCss.ts | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/node/build/buildPluginCss.ts b/src/node/build/buildPluginCss.ts index c14131e1184cd0..7657c8e219e7b9 100644 --- a/src/node/build/buildPluginCss.ts +++ b/src/node/build/buildPluginCss.ts @@ -22,7 +22,7 @@ import slash from 'slash' const debug = require('debug')('vite:build:css') const cssInjectionMarker = `__VITE_CSS__` -const cssInjectionRE = /__VITE_CSS__\(\)/g +const cssInjectionRE = /__VITE_CSS__\(\);?/g interface BuildCssOption { root: string @@ -45,9 +45,11 @@ export const createBuildCssPlugin = ({ preprocessOptions, modulesOptions = {} }: BuildCssOption): Plugin => { - const styles: Map = new Map() + const styles = new Map() let staticCss = '' + const emptyChunks = new Set() + return { name: 'vite:css', async transform(css: string, id: string) { @@ -156,6 +158,10 @@ export const createBuildCssPlugin = ({ if (cssCodeSplit) { code = code.replace(cssInjectionRE, '') + if (!code.trim()) { + // this is a shared CSS-only chunk that is empty. + emptyChunks.add(chunk.fileName) + } // for each dynamic entry chunk, collect its css and inline it as JS // strings. if (chunk.isDynamicEntry && chunkCSS) { @@ -184,6 +190,24 @@ export const createBuildCssPlugin = ({ staticCss = minifyCSS(staticCss) } + // remove empty css chunks and their imports + if (emptyChunks.size) { + emptyChunks.forEach((fileName) => { + delete bundle[fileName] + }) + const emptyChunkFiles = [...emptyChunks].join('|').replace(/\./g, '\\.') + const emptyChunkRE = new RegExp( + `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?`, + 'g' + ) + for (const file in bundle) { + const chunk = bundle[file] + if (chunk.type === 'chunk') { + chunk.code = chunk.code.replace(emptyChunkRE, '') + } + } + } + if (staticCss) { this.emitFile({ name: 'style.css',