Search code examples
cssreactjsrolluppostcssrollup-plugin-postcss

What is the right way to ship css in a react library?


I am developing my own library of react components. I am using rollup to create the build. I also want to ship css along with it which i bundled into a single styles.css file. My concern is how a user would use it. They can simply import the components using import { Component1, Component2 } from 'my-library' but they are not styled by default. This can be solved by importing the css file: import 'my-library/build/styles.css' but i feel like this import is redundant, i want the css file to be included by default in my library index.js file. I am not sure how can i achieve this.

I am using rollup and rollup-plugin-postcss.

So my question is how do i do this? Should i use some rollup plugin? Is my idea right in the first place? Maybe i should leave it to the user to decide how they want it bundled because my approach forces them to use some loader for css files?


Solution

  • If you want to ship external styles (instead of e.g. a CSS-in-JS system such as Emotion), that "redundant import" way is the standard, exactly because you can't know how the user of your library wants the styles applied to their page, or which loader (or bundler!) they'd want to use.

    It's also possible there's no document to inject styles into at all, in case your users are server-side-rendering your component to be hydrated on the client side.