1

I've been looking for a good way to style a react component just using css stylesheets. I would have used style-loader, because it's as easy as require('./style.css') and allows to save the final styles into a stylesheet file for production, but... I'm trying to make a shareable react component (I will publish it as a library for anyone to use), so using webpack or other kinds of bundling is not going to work (otherwise React library will get bundled along with my code).

Is it ok to just leave require('./style.css') in my source code, and perhaps just assume that user will have the style-loader or something similar that can recognize requiring css assets? Or is there a more elegant way that would still be as easy as requiring stylesheets from JS, wouldn't need the user to have style-loder, and would be isomorphic?

Please don't offer me to use styled-components or inline styles. Stylesheets offer much more functionality, and I'm not willing to sacrifice it.

3
  • "so using webpack or other kinds of bundling is not going to work" -- You could still whatever bundler you want, and publish the output of the bundler to NPM.
    – Samuel
    Jul 9, 2017 at 21:01
  • @Samuel - if I use any bundler, then things like React, module loading system, even style-loader system, will get bundled along with my code. Obviously, all I want to publish is just my code excluding those bits, because the user will definitely include their own React version, probably their own bundling and style-loading system, and I don't want them to have duplications in their code.
    – guitarino
    Jul 9, 2017 at 21:10
  • 2
    That situation is handled with marking React as a peerDependencies. docs.npmjs.com/files/package.json#peerdependencies and the bundler should only be put in devDependencies. Projects that depend on your project won't install any of the devDependencies.
    – Samuel
    Jul 9, 2017 at 21:27

1 Answer 1

2

No, please don't require the css file like that. That restricts the ways that your component can be used.

Its pretty common for people to run the same code base on the client and the server. Requiring a css file can't do anything useful when running on the server.

Instead, provide the css file in your bundle and document where it is. The end user can require() it, import it in a scss file, or whatever works for them. That gives you the best flexiblity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.