if you have a react component contains js and css, and you want to share it to the NPM then other developers only need to import your component in their js file just like using other common component, no need to separately import sass or css file
Almost four months ago, I created a react component called react-tooltip then shared it to the NPM. Besides importing js to start use, it also needs the users to import sass or css file into their project which I think is really inconvenient for those who build their project by using npm and browserify.
In that time, I checked other famous react component like react-select to see how they solve the problem, and I happened to see the author of react-select opens an issue to ask others how to contains his css into js, or you have to find the css file in node_modules/ folder then copy them to your project. Nobody gave a satisfied idea so I just let it go , then I wrote README to tell people where they can find css file of this component.
css-module and webpack
Recently I begin to use css-module and webpack in my daily work, and I got inspired by them about how to inject css file into your js. To summarize:
- Inject your css into style tag in <head />: I know inline css is hot in these days, but it can’t support pseudo class or pseudo element like :hover or :after.
- Transform class name to avoid class name conflict: because component css usually have a leading class and other css just nested under it(if you are using sass) , so transforming the leading class name is enough.
Implement and workflow
Train of though:
- use node-sass to transform sass into css
- write the output css into a js file which will exports a css string
- import the css string to your component
- insert css string into style tag when the component rendering
- delete the style tag when the component unmount
Let’s come to the point:
- Using node-sass to translate sass into a js file:
after use node to execute this file, you will get a js file(style.js) that exports a string which then you can insert it to the style tag.
2. import that new js file(style.js, transformed from previous step) into your component
Suit for NPM component
Actually I have tried a lot of methods to solve this problem, include RCSS, jsxstyle and css-modulesify. Unfortunately, they all can’t help me.
My current method may looks a little bit hack but what makes me happy is that I can still use sass and browserify to build my component. Maybe you never need this to build your large project but you can try this way if you want to build a NPM component contains not only js but also css.
This is my project address https://github.com/wwayne/react-tooltip , and welcome comments and advices.