Skip to content

Commit

Permalink
perf: remove empty chunk from css extraction
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Nov 22, 2020
1 parent 3aedea5 commit 963614b
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/node/build/buildPluginCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -45,9 +45,11 @@ export const createBuildCssPlugin = ({
preprocessOptions,
modulesOptions = {}
}: BuildCssOption): Plugin => {
const styles: Map<string, string> = new Map()
const styles = new Map<string, string>()
let staticCss = ''

const emptyChunks = new Set<string>()

return {
name: 'vite:css',
async transform(css: string, id: string) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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',
Expand Down

0 comments on commit 963614b

Please sign in to comment.