14

I'm running into some issues when trying to create a component library with RollupJS.

I'm building a react component library to be used inside other projects. The library uses css-modules for the styling of the components. I currently have a basic version of my component library, but when I use it in a Gatsby project, I get a FOUC (because the js gets injected into the head with javascript). This led mo to extract the CSS and inject it into the head of the consuming application, but I don't think this is the way to go.

What I would like to accomplish is that each component exposes its own stylesheet so the consuming application can import only the style of the components it needs. (An even better approach would be that we only need to import the component we need, and it will provide the CSS to the application, but that is phase 2)

My project structure looks like this

- src
  - components
    - component_1
        * index.js
        * styles.module.scss
    - component_2
        * index.js
        * styles.module.scss

To be able to reference the styles of each component separately I (think) I would need an output structure like

- dist
  - modules
    - components
      - component_1
        * … (files generated by rollup)
        * styles.css
      - component_2
        * … (files generated by rollup)
        * styles.css

I have been fiddling with my rollup setup and got to this point: The config below gives me one big index CSS file, but depending on how the library will grow, I don’t think it is good practice to always have to include all of the component styles (even those of components that aren’t used)

import babel from "rollup-plugin-babel";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import resolve from "rollup-plugin-node-resolve";
import prettier from "rollup-plugin-prettier";

export default {
    input: "src/index.js",
    output: [
        {
            dir: "build/modules",
            format: "esm",
            exports: "named",
            sourcemap: true,
        },
        {
            dir: "build/common",
            format: "cjs",
            exports: "named",
            sourcemap: true,
        },
    ],
    plugins: [
        peerDepsExternal(),
        resolve(),
        prettier({ parser: "babel" }),
        postcss({
            modules: true,
            extract: true,
        }),
        babel({
            exclude: "node_modules/**",
        }),
    ],
    external: ["react", "react-dom"],
    preserveModules: true,
};

Does anybody know how I could go about letting rollup create the CSS files on component level instead of on library level? I've gone through the options that rollup and rollup-plugin-postcss have to offer, but I don't see a solution for this issue.

WD86
  • 151
  • 4

0 Answers0