Skip to content

Commit

Permalink
Merge pull request #112 from nextcloud-libraries/fix/css-import-plugin
Browse files Browse the repository at this point in the history
fix(css-plugin): Use `generateBundle` hook to prevent CSS imports from being lost
  • Loading branch information
susnux authored Jan 29, 2024
2 parents 3386dff + 0a801cc commit 85a5da0
Showing 1 changed file with 36 additions and 16 deletions.
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

0 comments on commit 85a5da0

Please sign in to comment.