Search code examples
javascriptcssreactjsnpmsoftware-distribution

Distribute CSS with a React component


I have a React component index.js which has styling in style.css.

I want to distribute this component on npm, but I am confused about how I can make it easy for other developers to use the styling.

There are three options I have seen:

  • Use require('./style.css') and rely on the users having a bundling solution (e.g. webpack, rollup). I don't like this solution as it forces users down a certain route to use my component.
  • Make the user import the style with <link rel="stylesheet" href="node_modules/package/style.css" />. I don't like this solution as it means that my users will have to make changes to their HTML rather than just including the React component where they want it.
  • Put the CSS in the component itself with a plugin such as react-jss. This isn't a viable solution for me as I have a large number of SCSS files making up the styling for my component.

None of these solutions meet my needs and make it quite awkward to use my component. How can I distribute the component so that it's easy for people to use it?


Solution

  • Let the users choose how to include the file in their app. I'd suggest to add to your README.md:

    Don't forget to include the CSS file!

    Using ES6 with a module bundler like Webpack:

    import 'package/dist/style.css';
    

    Or, in plain old reliable HTML:

    <!DOCTYPE HTML>
    <html>
     <head>
       ...
       <link href="node_modules/package/dist/style.css" rel="stylesheet" />
       ...
     </head>
     ...
    </html>
    

    You can also use your own style.

    This is the approach taken by most packages: