vite-plugin-css-injected-by-js icon indicating copy to clipboard operation
vite-plugin-css-injected-by-js copied to clipboard

[Bug]: cssAssetsFilterFunction breaks dynamic imports

Open vovkiv94 opened this issue 10 months ago • 2 comments

🐞 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


vovkiv94 avatar Apr 16 '24 14:04 vovkiv94

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

marco-prontera avatar Apr 18 '24 20:04 marco-prontera

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;
}

vovkiv94 avatar Apr 22 '24 23:04 vovkiv94

Fixed v3.5.1

marco-prontera avatar Apr 27 '24 13:04 marco-prontera