Home  >  Q&A  >  body text

Split or inject styles in React component libraries built with Vite

I am currently rewriting the build steps for the component library to use Vite. I'm having an issue with styles, they are not split but bundled into one big style.css file. This brings me to two questions:

In my previous setup, I had style injection, which meant the CSS was injected into the component and therefore split. Can I achieve something similar with Vite?

My current build setup is this:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import dts from "vite-plugin-dts";

export default defineConfig({
  plugins: [react(), dts()],
  resolve: {
    alias: {
      "@": "/src"
    }
  },
  build: {
    outDir: "dist",
    lib: {
      entry: "src/index.ts",
      name: "lib",
      fileName: format => `lib.${format}.js`
    },
    rollupOptions: {
      external: ["react", "react-dom"],
      output: {
        globals: {
          react: "React",
          "react-dom": "ReactDOM"
        }
      }
    },
    sourcemap: true
  },
  css: {
    modules: {
      generateScopedName: "[name]__[local]___[hash:base64:5]"
    }
  }
});

The final dist folder looks like this (I excluded all .d.ts files):

As you can see, there is a big style.css, which is not what I'm looking for.

Is there a way to solve this problem?

P粉464113078P粉464113078253 days ago414

reply all(1)I'll reply

  • P粉007288593

    P粉0072885932024-01-11 15:47:29

    If you haven't solved the problem yet, the easiest way I could find is to add the plugin vite-plugin-css-injected-by-js to Vite to internalize the generated CSS to JS in the file.

    https://www.npmjs.com/package /vite-plugin-css-injected-by-js

    You can then change your vite config file to:

    import { defineConfig } from "vite";
    import react from "@vitejs/plugin-react";
    import dts from "vite-plugin-dts";
    // added the import for inject css automatically...
    import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'
    
    export default defineConfig({
      plugins: [
        react(), 
        dts(),
        cssInjectedByJsPlugin(),
      ],
      // ... rest of your vite configuration
    });

    reply
    0
  • Cancelreply