gajus/babel-plugin-react-css-modules — 2.0k★ on GitHub (JavaScript). Transforms styleName to className using compile time CSS module resolution.
Snapshot summary built from the project's own GitHub metadata — there's no written TopGit review yet. The page will update automatically when a full review is published.
WHY NO REVIEW YET
TopGit writes full reviews for the most-starred, most-requested repositories. This page is a snapshot until then — see the READ ME tab for the original README in full.
This project is not actively maintained by the original author. However, I am happy to nominate new maintainers.
If you wish to contribute to babel-plugin-react-css-modules, please begin by raising PRs that fix existing issues.
PRs must pass CI/CD tests, include tests (if they change behavior or fix a bug), and include documentation.
Transforms styleName to className using compile time CSS module resolution.
In contrast to react-css-modules, babel-plugin-react-css-modules has a lot smaller performance overhead (0-10% vs +50%; see Performance) and a lot smaller size footprint (less than 2kb vs 17kb react-css-modules + lodash dependency).
CSS Modules
Difference from react-css-modules
Performance
How does it work?
Conventions
Anonymous reference
Named reference
Configuration
Configurate syntax loaders
Custom Attribute Mapping
Installation
React Native
Demo
Example transpilations
Anonymous styleName resolution
Named styleName resolution
Runtime styleName resolution
Limitations
Have a question or want to suggest an improvement?
FAQ
How to migrate from react-css-modules to babel-plugin-react-css-modules?
How to reference multiple CSS modules?
How to live reload the CSS?
CSS Modules
CSS Modules are awesome! If you are not familiar with CSS Modules, it is a concept of using a module bundler such as webpack to load CSS scoped to a particular document. CSS module loader will generate a unique name for each CSS class at the time of loading the CSS document (Interoperable CSS to be precise). To see CSS Modules in practice, webpack-demo.
In the context of React, CSS Modules look like this:
react-css-modules introduced a convention of using styleName attribute to reference CSS module. react-css-modules is a higher-order React component. It is using the styleName value to construct the className value at the run-time. This abstraction frees a developer from needing to reference the imported styles object when using CSS modules (What's the problem?). However, this approach has a measurable performance penalty (see Performance).
babel-plugin-react-css-modules solves the developer experience problem without impacting the performance.
Performance
The important metric here is the "Difference from the base benchmark". "base" is defined as using React with hardcoded className values. The lesser the difference, the bigger the performance impact.
Note:
This benchmark suite does not include a scenario when babel-plugin-react-css-modules can statically construct a literal value at the build time.
If a literal value of the className is constructed at the compile time, the performance is equal to the base benchmark.
Must match webpack context configuration. css-loader inherits context values from webpack. Other CSS module implementations might use different context resolution logic.
process.cwd()
exclude
string
A RegExp that will exclude otherwise included files e.g., to exclude all styles from node_modules exclude: 'node_modules'
filetypes
?FiletypesConfigurationType
Configure postcss syntax loaders like sugarss, LESS and SCSS and extra plugins for them.
generateScopedName
?GenerateScopedNameConfigurationType
Refer to Generating scoped names. If you use this option, make sure it matches the value of localIdentName in webpack config. See this issue
[path]___[name]__[local]___[hash:base64:5]
removeImport
boolean
Remove the matching style import. This option is used to enable server-side rendering.
false
webpackHotModuleReloading
boolean
Enables hot reloading of CSS in webpack
false
handleMissingStyleName
"throw", "warn", "ignore"
Determines what should be done for undefined CSS modules (using a styleName for which there is no CSS module defined). Setting this option to "ignore" is equivalent to setting errorWhenNotFound: false in react-css-modules.
"throw"
attributeNames
?AttributeNameMapType
Refer to Custom Attribute Mapping
{"styleName": "className"}
skip
boolean
Whether to apply plugin if no matching attributeNames found in the file
false
autoResolveMultipleImports
boolean
Allow multiple anonymous imports if styleName is only in one of them.
false
Missing a configuration? Raise an issue.
Note:
The default configuration should work out of the box with the css-loader.
Option types (flow)
type FiletypeOptionsType = {|
+syntax: string,
+plugins?: $ReadOnlyArray<string | $ReadOnlyArray<[string, mixed]>>
|};
type FiletypesConfigurationType = {
[key: string]: FiletypeOptionsType
};
type GenerateScopedNameType = (localName: string, resourcePath: string) => string;
type GenerateScopedNameConfigurationType = GenerateScopedNameType | string;
type AttributeNameMapType = {
[key: string]: string
};
Configurate syntax loaders
To add support for different CSS syntaxes (e.g. SCSS), perform the following two steps:
Add the postcss syntax loader as a development dependency:
npm install postcss-scss --save-dev
Add a filetypes syntax mapping to the Babel plugin configuration. For example for SCSS:
NOTE: postcss-nested is added as an extra plugin for demonstration purposes only. It's not needed with postcss-scss because SCSS already supports nesting.
Postcss plugins can have options specified by wrapping the name and an options object in an array inside your config:
You can set your own attribute mapping rules using the attributeNames option.
It's an object, where keys are source attribute names and values are destination attribute names.
For example, the <NavLink> component from React Router has a activeClassName attribute to accept an additional class name. You can set "attributeNames": { "activeStyleName": "activeClassName" } to transform it.
The default styleName -> className transformation will not be affected by an attributeNames value without a styleName key. Of course you can use { "styleName": "somethingOther" } to change it, or use { "styleName": null } to disable it.
Installation
When babel-plugin-react-css-modules cannot resolve CSS module at a compile time, it imports a helper function (read Runtime styleName resolution). Therefore, you must install babel-plugin-react-css-modules as a direct dependency of the project.
npm install babel-plugin-react-css-modules --save
React Native
If you'd like to get this working in React Native, you're going to have to allow custom import extensions, via a rn-cli.config.js file:
Remember, also, that the bundler caches things like plugins and presets. If you want to change your .babelrc (to add this plugin) then you'll want to add the --reset-cache flag to the end of the package command.
Demo
git clone [email protected]:gajus/babel-plugin-react-css-modules.git
cd ./babel-plugin-react-css-modules/demo
npm install
npm start
open http://localhost:8080/
Conventions
Anonymous reference
Anonymous reference can be used when there is only one stylesheet import.
Format: CSS module name.
Example:
import './foo1.css';
// Imports "a" CSS module from ./foo1.css.
<div styleName="a"></div>;
Named reference
Named reference is used to refer to a specific stylesheet import.
Format: [name of the import].[CSS module name].
Example:
import foo from './foo1.css';
import bar from './bar1.css';
// Imports "a" CSS module from ./foo1.css.
<div styleName="foo.a"></div>;
// Imports "a" CSS module from ./bar1.css.
<div styleName="bar.a"></div>;
Example transpilations
Anonymous styleName resolution
When styleName is a literal string value, babel-plugin-react-css-modules resolves the value of className at the compile time.
When a file imports multiple stylesheets, you must use a named reference.
Have suggestions for an alternative behaviour?
Raise an issue with your suggestion.
Input:
import foo from './foo1.css';
import bar from './bar1.css';
<div styleName="foo.a"></div>;
<div styleName="bar.a"></div>;
Output:
import foo from './foo1.css';
import bar from './bar1.css';
<div className="foo___a"></div>;
<div className="bar___a"></div>;
Runtime styleName resolution
When the value of styleName cannot be determined at the compile time, babel-plugin-react-css-modules inlines all possible styles into the file. It then uses getClassName helper function to resolve the styleName value at the runtime.
Configure webpack to use HMR. Use --hot option if you are using webpack-dev-server.
Use style-loader to load the style sheets.
Note:
This enables live reloading of the CSS. To enable HMR of the React components, refer to the Hot Module Replacement - React guide.
Note:
This is a webpack specific option. If you are using babel-plugin-react-css-modules in a different setup and require CSS live reloading, raise an issue describing your setup.
I get a "Cannot use styleName attribute for style name '[X]' without importing at least one stylesheet." error
First, ensure that you are correctly importing the CSS file following the conventions.
If you are correctly importing but using different CSS (such as SCSS), this is likely happening because your CSS file wasn't able to be successfully parsed. You need to configure a syntax loader.
I get a "Could not resolve the styleName '[X]' error but the class exists in the CSS included in the browser.
First, verify that the CSS is being included in the browser. Remove from styleName the reference to the CSS class that's failing and view the page. Search through the <style> tags that have been added to the <head> and find the one related to your CSS module. Copy the code into your editor and search for the class name.
Once you've verified that the class is being rendered in CSS, the likely cause is that the babel-plugin-react-css-modules is unable to find your CSS class in the parsed code. If you're using different CSS (such as SCSS), verify that you have configured a syntax loader.
However, if you're using a syntaxes such as postcss-scss or postcss-less, they do not compile down to CSS. So if you are programmatically building a class name (see below), webpack will be able to generate the rendered CSS from SCSS/LESS, but babel-plugin-react-css-modules will not be able to parse the SCSS/LESS.
babel-plugin-react-css-modules will not receive icon-10 or icon-50, but icon-#{$scale}. That is why you receive the error that styleName"icon-10" cannot be found.
How active is development on gajus/babel-plugin-react-css-modules?
The most recent commit recorded on gajus/babel-plugin-react-css-modules was 4.3 years ago, based on the GitHub push timestamp. The repository has 158 forks — one of the better signals of community interest.
How many stars does gajus/babel-plugin-react-css-modules have?
gajus/babel-plugin-react-css-modules has 2.0k GitHub stars — refresh the page for the live number, or check github.com/gajus/babel-plugin-react-css-modules. TopGit mirrors GitHub's count but does not claim minute-by-minute accuracy.
What else is in the Frontend space?
gajus/babel-plugin-react-css-modules is tracked by TopGit under the Frontend category, alongside 3 GitHub-tagged topics. Trending and Topics pages list peer repositories of comparable stars and language.
What language is gajus/babel-plugin-react-css-modules written in?
gajus/babel-plugin-react-css-modules is written primarily in JavaScript. GitHub's language field is based on the largest share of bytes in the default branch.
What topics is gajus/babel-plugin-react-css-modules associated with?
GitHub's repository topics for gajus/babel-plugin-react-css-modules: "babel-plugin", "css-modules", "react". TopGit's editorial category is Frontend.
Where do I read more about gajus/babel-plugin-react-css-modules?
This TopGit page is a snapshot — the READ ME tab shows the project's own README content (links stripped, images preserved). The GitHub repository at github.com/gajus/babel-plugin-react-css-modules is the definitive source.
Why is gajus/babel-plugin-react-css-modules categorized under Frontend?
TopGit places gajus/babel-plugin-react-css-modules in the Frontend category based on its GitHub topics and description (tagged: "babel-plugin", "css-modules", "react"). Categories are assigned from real repository metadata, not editorial guesswork.
Read full README in the tab above.
Is babel-plugin-react-css-modules worth your time?
ChatGPT, Claude and Perplexity can all read this page. Ask one of them what it makes of babel-plugin-react-css-modules.