How to use babel-plugin-react-css-modules without ejecting?
See original GitHub issueTL;DR; Asking for pointers on using babel-plugin-react-css-modules
without ejecting.
Hi fellow create-react-app
users,
I’m a new user to this amazing tool, having only used React on Rails projects using Webpacker (I’m mostly a Ruby developer myself). I’ve been following courses on several resources and I got caught up on the whole styling React thing; so far choosing CSS modules as my favorite approach.
Previously, I configured CSS modules by ejecting, but now that create-react-app
2 is on the way I see CSS modules are coming with just an extension change. Great!
However, I also saw that babel-plugin-react-css-modules
is being favored over react-css-modules
, in order to be able to use styleName
and gaining all the performance benefits.
So I read about having to use Babel Macros to use this without ejecting. But if I don’t know how to create a plugin/macro, do I need to stick with importing styles as an object and using className?
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (2 by maintainers)
It seems that you want too use
babel-plugin-react-css-modules
overreact-css-modules
, but CRA v2 doesn’t use either. It’s using postcss under the hood (relevant PR). It’s probably useful to understand why CRA is using postcss at compile-time because it negates all the worry about runtime costs and bloat that thebabel-plugin-react-css-modules
talks about.If you want to use
babel-plugin-react-css-modules
, then this isn’t supported by CRA and imho likely won’t be since its semantics deviate pretty heavily from the straightforward, opt-in version of CSS modules that CRA v2 currently supports.My recommendation would be either to eject or use react-app-rewired@next to override the portions of the webpack / babel config that you need, but be aware that this essentially “voids the warranty” provided by base CRA in terms of guaranteeing how things work.
With that being said, my 95% recommendation would be to just use the built-in CRA support for CSS modules and not complicate things any further 😉
Thank you @patricklafrance, that was super helpful.
FYI for all, just to be clear, babel-plugin-react-css-modules doesn’t replace postcss for CSS Modules. It doesn’t really do anything with processing the CSS files themselves at all. It’s purely a React helper that lets you use an alternate syntax. So instead of this:
You can use this:
The alternate syntax is nice, but the main benefit for me is that with the babel plugin in place, you get error messages when you fat finger a local class name and spell it wrong.