marco-prontera / vite-plugin-css-injected-by-js

A Vite plugin that takes the CSS and adds it to the page through the JS. For those who want a single JS file.
MIT License
429 stars 26 forks source link

[Bug]: cssAssetsFilterFunction breaks dynamic imports #142

Closed vovkiv94 closed 7 months ago

vovkiv94 commented 7 months ago

🐞 Bug Report

Describe the bug

I have a use case where I want to inline only entry css but keep separate css files for dynamically imported modules.

cssAssetsFilterFunction: function customCssAssetsFilterFunction(outputAsset) {
    return outputAsset.fileName === 'index.css';
  }

It inlines index.css as expected, it also creates css files for dynamically imported modeuls, but the issue is that the css files are not loaded anymore since they are removed from the metadata by clearImportedCssViteMetadataFromBundle

*


Is this a regression?


To Reproduce

  1. Create react app
  2. Lazy load one of the commponents(make sure it imports some styles)
  3. Setup the plugin but filter out all files but index.css
  4. Build and run the app in the preview mode, the css for dynamic modules is not loading.

Expected behaviour

I expect filtered out css for dynamically imported modules to work as without the plugin


marco-prontera commented 7 months ago

Hi can you provide to me the full configuration of Vite also with this plugin?

vovkiv94 commented 7 months ago

vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    cssInjectedByJsPlugin({
      cssAssetsFilterFunction: function customCssAssetsFilterFunction(outputAsset) {
        return outputAsset.name === 'index.css';
      }
    }),
  ]
})

main.tsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

index.css

.test {
  background-color: red;
  width: 100px;
  height: 100px;
}

App.tsx

import {lazy, Suspense} from "react";

const Dynamic = lazy(() => import('./Dynamic.js'));

function App() {
  return (
    <>
      <div className="test"></div>
      <Suspense><Dynamic/></Suspense>
    </>
  )
}

export default App

Dynamic.tsx

import './dynamic.css';

function Dynamic() {
  return (
    <div className="dynamic-test"></div>
  )
}

export default Dynamic

dynamic.css

.dynamic-test {
    background-color: green;
    width: 100px;
    height: 100px;
}
marco-prontera commented 7 months ago

Fixed v3.5.1