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:
style.css
doesn't magically get imported. 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. p>
Is there a way to solve this problem?
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: