Skip to content

Commit

Permalink
refactor(css): inject viteNonFinalizedFilename to detect pure CSS c…
Browse files Browse the repository at this point in the history
…hunks
  • Loading branch information
sapphi-red committed Jul 28, 2023
1 parent 1292ad0 commit 243e10b
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import {
arraify,
arrayEqual,
asyncReplace,
cleanUrl,
combineSourcemaps,
Expand Down Expand Up @@ -71,6 +70,13 @@ import {
} from './asset'
import type { ESBuildOptions } from './esbuild'

declare module 'rollup' {
export interface RenderedChunk {
/** @internal */
viteNonFinalizedFilename: string
}
}

// const debug = createDebugger('vite:css')

export interface CSSOptions {
Expand Down Expand Up @@ -527,6 +533,8 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
},

async renderChunk(code, chunk, opts) {
chunk.viteNonFinalizedFilename = chunk.fileName // save non finalized

let chunkCSS = ''
let isPureCssChunk = true
const ids = Object.keys(chunk.modules)
Expand Down Expand Up @@ -734,21 +742,17 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
// remove empty css chunks and their imports
if (pureCssChunks.size) {
// map each pure css chunk (rendered chunk) to it's corresponding bundle
// chunk. we check that by comparing the `moduleIds` as they have different
// filenames (rendered chunk has the !~{XXX}~ placeholder)
const pureCssChunkNames: string[] = []
for (const pureCssChunk of pureCssChunks) {
for (const key in bundle) {
const bundleChunk = bundle[key]
if (
bundleChunk.type === 'chunk' &&
arrayEqual(bundleChunk.moduleIds, pureCssChunk.moduleIds)
) {
pureCssChunkNames.push(key)
break
}
}
}
// chunk. we check that by `viteNonFinalizedFilename` as they have different
// `filename`s (rendered chunk has the !~{XXX}~ placeholder)
const finalizedFilenamesMap = Object.fromEntries(
Object.values(bundle)
.filter((chunk): chunk is OutputChunk => chunk.type === 'chunk')
.map((chunk) => [chunk.viteNonFinalizedFilename, chunk.fileName]),
)

const pureCssChunkNames = [...pureCssChunks].map(
(pureCssChunk) => finalizedFilenamesMap[pureCssChunk.fileName],
)

const emptyChunkFiles = pureCssChunkNames
.map((file) => path.basename(file))
Expand Down

0 comments on commit 243e10b

Please sign in to comment.