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

fix(css-plugin): Use generateBundle hook to prevent CSS imports from being lost #112

Merged
merged 1 commit into from
Jan 29, 2024
Merged
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
52 changes: 36 additions & 16 deletions lib/plugins/ImportCSS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,43 @@ export const ImportCSSPlugin: () => Plugin = () => {
return {
name: 'vite-import-css-libmode',
enforce: 'post',
renderChunk(code, chunk) {
if (!chunk.viteMetadata) return
const { importedCss } = chunk.viteMetadata
if (!importedCss.size) return
/**
* Add imports for all splitted CSS assets back to the places where the CSS is used.
*
* We must use `generateBundle` as Vite removes "empty css chunks" (chunks that only import css)
* in its `generateBundle` hook and merged the `importedCss` property down to the really emitted chunks.
* Otherwise we will loose CSS imports!
*
* @param options Output options
* @param bundle The output bundle
*/
generateBundle(options, bundle) {
for (const filename in bundle) {
const chunk = bundle[filename]
// Make sure chunk is an output chunk with meta data
if (!('viteMetadata' in chunk) || !chunk.viteMetadata) {
continue
}

/**
* Inject the referenced style files at the top of the chunk.
*/
const ms = new MagicString(code)
for (const cssFileName of importedCss) {
let cssFilePath = relative(dirname(chunk.fileName), cssFileName)
cssFilePath = cssFilePath.startsWith('.') ? cssFilePath : `./${cssFilePath}`
ms.prepend(`import '${cssFilePath}';\n`)
}
return {
code: ms.toString(),
map: ms.generateMap(),
// Check if the chunk imported CSS, if not we can skip
const { importedCss } = chunk.viteMetadata
if (!importedCss.size) {
continue
}

// Inject the referenced style files at the top of the chunk.
const ms = new MagicString(chunk.code)
for (const cssFileName of importedCss) {
let cssFilePath = relative(dirname(chunk.fileName), cssFileName)
cssFilePath = cssFilePath.startsWith('.') ? cssFilePath : `./${cssFilePath}`
if (options.format === 'es') {
ms.prepend(`import '${cssFilePath}';\n`)
} else {
ms.prepend(`require('${cssFilePath}');\n`)
}
}
chunk.code = ms.toString()
chunk.map = ms.generateMap()
}
},
}
Expand Down
Loading