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:
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.<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.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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With