diff --git a/lib/plugins/ImportCSS.ts b/lib/plugins/ImportCSS.ts index 966a317..304359f 100644 --- a/lib/plugins/ImportCSS.ts +++ b/lib/plugins/ImportCSS.ts @@ -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() } }, }