Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@dr.pogodin/babel-plugin-react-css-modules
Advanced tools
Transforms styleName to className using compile time CSS module resolution.
This is an up-to-date version of babel-plugin-react-css-modules
:
css-loader
versions (see
compatibility table for details).To migrate from the original babel-plugin-react-css-modules
just prefix its name in your Babel config by @dr.pogodin/
scope, i.e.:
@dr.pogodin/babel-plugin-react-css-modules
or @dr.pogodin/react-css-moudles
instead of babel-plugin-react-css-modules
or react-css-modules
.css-loader versions | this plugin versions |
---|---|
5.2.4 | 6.1.0 |
5.1.3 ÷ 5.2.3 | N/A |
5.0.0 ÷ 5.1.2 | 6.0.7 ÷ 6.0.11 |
4.2.0 ÷ 4.3.0 | 6.0.3 ÷ 6.0.6 |
<= 3.6.0 | original plugin |
css-loader
: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).
react-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:
import React from 'react';
import styles from './table.css';
export default class Table extends React.Component {
render () {
return <div className={styles.table}>
<div className={styles.row}>
<div className={styles.cell}>A0</div>
<div className={styles.cell}>B0</div>
</div>
</div>;
}
}
Rendering the component will produce a markup similar to:
<div class="table__table___32osj">
<div class="table__row___2w27N">
<div class="table__cell___1oVw5">A0</div>
<div class="table__cell___1oVw5">B0</div>
</div>
</div>
and a corresponding CSS file that matches those CSS classes.
Awesome!
However, there are several disadvantages of using CSS modules this way:
camelCase
CSS class names.styles
object whenever constructing a className
.undefined
without a warning.babel-plugin-react-css-modules
automates loading of CSS Modules using styleName
property, e.g.
import React from 'react';
import './table.css';
export default class Table extends React.Component {
render () {
return <div styleName='table'>
<div styleName='row'>
<div styleName='cell'>A0</div>
<div styleName='cell'>B0</div>
</div>
</div>;
}
}
Using babel-plugin-react-css-modules
:
You are not forced to use the camelCase
naming convention.
You do not need to refer to the styles
object every time you use a CSS Module.
There is clear distinction between global CSS and CSS modules, e.g.
<div className='global-css' styleName='local-module'></div>
react-css-modules
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.
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 theclassName
is constructed at the compile time, the performance is equal to the base benchmark.
Name | Operations per second (relative margin of error) | Sample size | Difference from the base benchmark |
---|---|---|---|
Using className (base) | 9551 (±1.47%) | 587 | -0% |
react-css-modules | 5914 (±2.01%) | 363 | -61% |
babel-plugin-react-css-modules (runtime, anonymous) | 9145 (±1.94%) | 540 | -4% |
babel-plugin-react-css-modules (runtime, named) | 8786 (±1.59%) | 527 | -8% |
Platform info:
- Darwin 16.1.0 x64
- Node.JS 7.1.0
- V8 5.4.500.36
- NODE_ENV=production
- Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz × 8
View the ./benchmark.
Run the benchmark:
git clone git@github.com:birdofpreyru/babel-plugin-react-css-modules.git
cd ./babel-plugin-react-css-modules
npm install
npm run build
cd ./benchmark
npm install
NODE_ENV=production ./test
.css
or .scss
extension).styleName
attribute value into anonymous and named CSS module references.styleName
value is a string literal, generates a string literal value.styleName
value is a jSXExpressionContainer
, uses a helper function (getClassName
) to construct the className
value at the runtime.styleName
attribute from the element.className
to the existing className
value (creates className
attribute if one does not exist).Configure the options for the plugin within your .babelrc
as follows:
{
"plugins": [
["@dr.pogodin/react-css-modules", {
"option": "value"
}]
]
}
Name | Type | Description | Default |
---|---|---|---|
context | string | 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.
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
};
To add support for different CSS syntaxes (e.g. SCSS), perform the following two steps:
npm install postcss-scss --save-dev
filetypes
syntax 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-nested
is added as an extra plugin for demonstration purposes only. It's not needed withpostcss-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:
"plugins": [
["postcss-import-sync2", {
"path": ["src/styles", "shared/styles"]
}],
"postcss-nested"
]
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.
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 @dr.pogodin/babel-plugin-react-css-modules --save
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.
git clone git@github.com:birdofpreyru/babel-plugin-react-css-modules.git
cd ./babel-plugin-react-css-modules/demo
npm install
npm start
open http://localhost:8080/
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 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>;
styleName
resolutionWhen styleName
is a literal string value, babel-plugin-react-css-modules
resolves the value of className
at the compile time.
Input:
import './bar.css';
<div styleName="a"></div>;
Output:
import './bar.css';
<div className="bar___a"></div>;
styleName
resolutionWhen 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>;
styleName
resolutionWhen 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.
Input:
import './bar.css';
<div styleName={Math.random() > .5 ? 'a' : 'b'}></div>;
Output:
import _getClassName from 'babel-plugin-react-css-modules/dist/browser/getClassName';
import foo from './bar.css';
const _styleModuleImportMap = {
foo: {
a: 'bar__a',
b: 'bar__b'
}
};
<div styleName={_getClassName(Math.random() > .5 ? 'a' : 'b', _styleModuleImportMap)}></div>;
babel-plugin-react-css-modules
users? Chat on Gitter.Follow the following steps:
react-css-modules
.babel-plugin-react-css-modules
..babelrc
(see Configuration).cssModules
decorator and/or HoC.If you are still having problems, refer to one of the user submitted guides:
react-css-modules
had an option allowMultiple
. allowMultiple
allows multiple CSS module names in a styleName
declaration, e.g.
<div styleName='foo bar' />
This behaviour is enabled by default in babel-plugin-react-css-modules
.
babel-plugin-react-css-modules
utilises webpack Hot Module Replacement (HMR) to live reload the CSS.
To enable live reloading of the CSS:
webpackHotModuleReloading
babel-plugin-react-css-modules
configuration.webpack
to use HMR. Use --hot
option if you are using webpack-dev-server
.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.
[X]
' without importing at least one stylesheet." errorFirst, 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.
[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.
A SCSS example:
$scales: 10, 20, 30, 40, 50;
@each $scale in $scales {
.icon-#{$scale} {
width: $scale;
height: $scale;
}
}
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.
FAQs
Transforms styleName to className using compile time CSS module resolution.
The npm package @dr.pogodin/babel-plugin-react-css-modules receives a total of 3,308 weekly downloads. As such, @dr.pogodin/babel-plugin-react-css-modules popularity was classified as popular.
We found that @dr.pogodin/babel-plugin-react-css-modules demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.