Split or inject styles in React component libraries built with Vite
P粉464113078
P粉464113078 2024-01-10 17:00:11
0
1
411

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:

  • When I install the package into another project, it is not included automatically. If I import a component, style.css doesn't magically get imported.
  • I'm importing styles for a component that I'm not actually using.

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粉464113078
P粉464113078

reply all(1)
P粉007288593

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
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!