Babel plugin for advanced CSS modules support in React:
-
It transforms
styleNameattributes of JSX components intoclassNameusing compile-time CSS module resolution, allowing for a cleaner use of CSS modules in React. -
For server-side rendering (SSR) it can replace named stylesheet imports by class name mapping objects, and remove anonymous stylesheet imports.
This plugin is a fork and further evolution of the original
babel-plugin-react-css-modules (the original babel-plugin-react-css-modules
has been abandoned by its owner since 2019, and it does not work with the modern
Webpack versions).
Assuming style.css in the following examples is compiled as CSS Module.
Without this plugin
import S from './styles.css';
export default function Component() {
return (
<div className={S.container}>
<h1 className={S.title}>Example</div>
<p styleName={S.text}>Sample text paragraph.</p>
<p className={`${S.text} ${S.special}`}>
Sample text paragraph with special style.
</p>
</div>
);
}With this plugin
import './styles.css';
export default function Component() {
return (
<div styleName="container">
<h1 styleName="title">Example</div>
<p styleName="text">Sample text paragraph.</p>
<p styleName="text special">
Sample text paragraph with special style.
</p>
</div>
);
}With this plugin and multiple stylesheets
Assuming:
- Styles
container,title, andtextare defined instyles-01.css. - Style
specialis defined instyles-02.css. - The plugin's
autoResolveMultipleImportsoption is enabled (default).
import './styles-01.css';
import './styles-02.css';
export default function Component() {
return (
<div styleName="container">
<h1 styleName="title">Example</div>
<p styleName="text">Sample text paragraph.</p>
<p styleName="text special">
Sample text paragraph with special style.
</p>
</div>
);
}If both files, styles-01.css and styles-02.css contain styles with the same
names, thus making auto resolution impossible, this plugin allows explicit
stylesheet prefixes:
import S1 from './styles-01.css';
import S2 from './styles-02.css';
export default function Component() {
return (
<div styleName="S1.container">
<h1 styleName="S1.title">Example</div>
<p styleName="S1.text">Sample text paragraph.</p>
<p styleName="S1.text S2.special">
Sample text paragraph with special style.
</p>
</div>
);
}With this plugin and runtime resolution
import './styles-01.css';
import './styles-02.css';
export default function Component({ special }) {
let textStyle = 'text';
if (special) textStyle += ' special';
return (
<div styleName="container">
<h1 styleName="title">Example</div>
<p styleName={textStyle}>Sample text paragraph.</p>
<p styleName={textStyle}>
Sample text paragraph with special style.
</p>
</div>
);
}In the case when the exact style value is not known at the compile time, like in
this example, the plugin will inject necessary code to correctly resolve the
styleName at runtime (which is somewhat less performant, but otherwise works
fine).
SSR scenario
Consider such component, which uses a named stylesheet import in order to use it in some other ways, beside simple styling, e.g. to also display the classname mapping:
import S from './style.css';
export default function Component() {
return (
<div styleName="container">
{JSON.stringify(S)}
</div>
)
}While by default this plugin transforms it into the following code (leaving it
to Webpack to handle ./style.scss import for the actual CSS bundling,
and to generate the correct JS output):
import S from './style.css';
export default function Component() {
return (
<div className="12345">
{JSON.stringify(S)}
</div>
)
}For server-side environment, if you don't compile server-side code with Webpack,
you'll need to replace ./style.css with valid JS code. That is exactly what
this plugin does with replaceImport option enabled, it outputs:
const S = {
container: '12345',
// Other stylesheet keys, if any.
};
export default function Component() {
return (
<div className="12345">
{JSON.stringify(S)}
</div>
)
}CommonJS require() support
The plugin works the same with require('./style.css') CSS imports.
-
The core CSS Modules functionality should be enabled and configured elsewhere in your React project:
- With bare Webpack see Native CSS.
- With other frameworks refer to their corresponding documentation.
-
Install this plugin as a direct dependency (in the edge-cases, when the compile-time
styleNameresolution is impossible, this plugin falls back to the runtime resolution).npm install --save @dr.pogodin/babel-plugin-react-css-modules
-
Install Webpack at least as a development dependency:
npm install --save-dev webpack
-
Add this plugin to Babel configuration:
{ "plugins": [ ["@dr.pogodin/react-css-modules", { "context": "/your/webpack/compilation/context", "localIdentName": "[fullhash:base64:6]", "uniqueName": "output.uniqueName used by Webpack", }] ] }BEWARE:
-
The
localIdentNameoption value MUST match thelocalIdentNameoption of the Webpack's CSS generator. By default, Webpack uses[uniqueName]-[id]-[local]for development builds, and[fullhash]for production builds (see: https://webpack.js.org/guides/native-css/#generator-options); we recommend to explicitly set the same, matching values both in this plugin's and in the Webpack generator's configurations, including the hash digest kind & length (e.g.[fullhash:base64:6]). -
The
fullhashcalculated by Webpack includes the path of CSS file, relative to the Webpack's compilationcontext, and the output.uniqueName value. Be sure to setcontextanduniqueNamesettings of this plugin to the appropriate values, and double-check the class names generated by Webpack, and by this plugin do match. -
Alternatively, this plugin provides a simplified, stable implementation for
getLocalIdentfunction (taken from a selected old version of css-loader). It only supports class name placeholders supported by the interpolateName() function ofloader-utils, but it resolves CSS file paths relative to the closestpackage.jsonfile, it does not factoruniqueNameinto the hash, and it supports an additionalpackageplaceholder, which is substituded by thenamevalue from the closestpackage.json— these come handy for compilation of libraries.You can use this
getLocalIdentfunction (its factory, to be precise) like this:Within Webpack Config
import { localIdentNameFactory } from '@dr.pogodin/babel-plugin-react-css-modules/utils'; export { module: { generator: { 'css/module': { localIdentName: localIdentNameFactory('[fullhash:base64:6]'), }, }, }, };
Within Babel Config
import { localIdentNameFactory } from '@dr.pogodin/babel-plugin-react-css-modules/utils'; export { plugins: [ ["@dr.pogodin/react-css-modules", { localIdentName: localIdentNameFactory('[fullhash:base64:6]'), // NOTE: No need for `context` and `uniqueName` settings here. }] ] };
-
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:
module.exports = {
getAssetExts() {
return ["scss"];
}
}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.
v8 version of this plugin drops compatibility with now deprecated css-loader (the old way to process CSS with Webpack), and aims to be compatible with Native CSS processing instead. To migrate:
-
Switch to Native CSS in your Webpack configuration.
-
Upgrade this plugin to v8 version, and update its configuration:
-
Replace
generateScopedNameoption bylocalIdentName.If you used a string value, be sure to set
contextanduniqueNameoptions of this plugin to matchcontextand output.uniqueName values used by Webpack.If you used
getLocalIdent()&generateScopedName()functions exported by this plugin, replace them by the newlocalIdentNameFactory()export. -
Be sure to double-check that class names generated by Webpack and this plugin are matching each other. In particular, Webpack includes into hashes the paths of CSS files relative to the context, and output.uniqueName values, it is easy to make a mistake and end up with Webpack and this plugin getting different values of these parameters.
-
These are valid plugin options. All are optional, but the overall configuration should be compatible with that of Webpack, thus defaults may not work for you.
-
context— string — Must match Webpackcontext. Defaultsprocess.cwd(). -
exclude— string — A RegExp that will exclude otherwise included files e.g., to exclude all styles fromnode_modules:exclude: 'node_modules'. -
filetypes— Configurate syntax loaders like sugarss, LESS and SCSS, and extra plugins for them. -
localIdentName— function | string — Allows to customize the exactstyleNametoclassNameconversion algorithm. For details see Generating scoped names. Defaults[file]__[local]__[hash:base64:6]. -
replaceImport— boolean — Replaces / removes stylesheet imports for server-side rendering purposes. See details below. Defaults false. -
handleMissingStyleName—ignore|throw|warn— Determines what should be done for undefined CSS modules (using astyleNamefor which there is no CSS module defined). Defaults"throw". -
attributeNames— Custom Attribute Mapping -
skip— boolean — Whether to apply plugin if no matchingattributeNamesfound in the file. Defaults false. -
transform — function — If provided, each CSS source loaded by the plugin will be passed through this function, alongside its path, and this plugin's options, and the output of this function will be used in place of the original CSS.
-
autoResolveMultipleImports— boolean — Allows multiple anonymous imports ifstyleNameis only in one of them. Defaults true.
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
filetypessyntax mapping to the Babel plugin configuration. For example for SCSS:"filetypes": { ".scss": { "syntax": "postcss-scss" } }
And optionally specify extra plugins:
"filetypes": { ".scss": { "syntax": "postcss-scss", "plugins": [ "postcss-nested" ] } }
NOTE:
postcss-nestedis added as an extra plugin for demonstration purposes only. It's not needed withpostcss-scssbecause SCSS already supports nesting.Postcss plugins can have options specified by wrapping the name and an options object in an array inside your config:
"plugins": [ ["postcss-import-sync2", { "path": ["src/styles", "shared/styles"] }], "postcss-nested" ]
function transform(cssSource, cssSourceFilePath, pluginOptions): stringThe transform function, if provided as the transform option of this plugin,
will be called for each loaded CSS source with three arguments:
cssSource— string — The loaded CSS code.cssSourceFilePath— string — The path of loaded CSS file.pluginOptions— object — The options set for this plugin.
It should return a string, the actual CSS code to use.
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 an 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.
If replaceImport flag is set, this plugin will remove or replace original
stylesheet imports, which is needed for server-side rendering:
// Anonymous imports are removed from the code:
import 'path/to/style.css';
// Default and named imports are replaced in the following manner:
// Before:
import styles, {
className,
otherClassName as alias,
} from 'path/to/style.css';
// After:
const styles = {
className: 'generatedClassName',
otherClassName: 'otherGeneratedClassName',
},
className = 'generatedClassName',
alias = 'otherGeneratedClassName';
// Also this kind of import:
import * as style from 'path/to/style.css';
// is replaced by:
const style = {
className: 'generatedClassName',
otherClassName: 'otherGeneratedClassName',
};This plugin does the following:
-
Builds the index of all stylesheet imports per file (imports of files with
.css, and other configured CSS extensions). -
Uses postcss to parse the matching CSS files into a lookup of CSS module references.
-
Iterates through all JSX element declarations.
-
Parses the
styleName(and/or other configured) attribute values into anonymous and named CSS module references. -
Finds the CSS class name matching the CSS module reference:
- If
styleNamevalue is a string literal, generates a string literal value. - If
styleNamevalue is ajSXExpressionContainer, uses a helper function (getClassName) to construct theclassNamevalue at the runtime.
- If
-
Removes the
styleNameattribute from the element. -
Appends the resulting
classNameto the existingclassNamevalue (createsclassNameattribute if one does not exist). -
With the
replaceImportfeature enabled, it also removes anonymous style imports from the code, and replaces named imports by the corresponding constant declarations.
This plugin is a fork and further evolution of the original babel-plugin-react-css-modules.
-
The original plugin has been abandoned by its owner since 2019, and does not work with modern Webpack versions since 2020.
-
This fork, created in 2020, receives regular maintenance, works with the latest Webpack versions, and gets new features as necessary.
There is no reference to this fork in the original plugin's repository because the owner of the original plugin removed announcements of this fork from his repository, and banned this fork's author from further commenting in there — he had no time to care about his stale plugin, but he has found a moment to spoil chances of users to find a working alternative.
The original plugin, and the versions of this fork prior to its v8 aimed for
compatibility with now deprecated css-loader (the legacy way to process CSS
by Webpack, replaced by Native CSS). If you still need to work with css-loader
in your project, consult
the css-loader compatibility
table of for plugin versions.