Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 406
James Monger Avatar asked Dec 24 '22 20:12

James Monger


2 Answers

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:

  • React Bootstrap
  • Blueprint
  • React Dates
  • React Tags Input
  • etc.
like image 171
GG. Avatar answered Dec 27 '22 20:12

GG.


To extend from GG's answer an advanced version would be to add js version of the css file.

Because this

import 'package/dist/style.css';

requires users to have Webpack configured to load css which might not be the case. For example I rarely do because I use css-in-js tools for my styling needs.

Instead if you wrap the css file into something like this:

package/dist/style.js

var insertCss = require('insert-css'); // https://github.com/substack/insert-css
// inline the whole style.css here
insertCss(".YourComponent { color: blue }");

Then the users can just do

import 'package/dist/style';

and it will work always with any module loader (Webpack, Browserify, Rollup...) regardless of their configuration.

like image 36
Epeli Avatar answered Dec 27 '22 22:12

Epeli