react-dynamic-css-plugin
v1.2.0
Published
Webpack plugin to transform dynamic react class names to short prefixed and obfuscated classes at runtime
Downloads
39
Maintainers
Readme
react-dynamic-css-plugin
Webpack plugin to transform dynamic react class names to short prefixed and obfuscated classes at runtime
Example:
Format to add a prefix and obfuscate the class names:
"pf_[md4:hash:base64:5]";
The dynamic nature means that runtime generated classes get transformed
Input:
<MyComponent className={["my-component", `is-disabled_${disabled}`].join()} />
Evaluated:
<MyComponent className={"my-component is-disabled_true"} />
Output:
<div class="pf_Xscyf pf_LfRuA"></div>
.pf_Xscyf.pf_LfRuA {
//Styles
}
Installation
npm install react-dynamic-css-plugin --save-dev
Usage
webpack.config.js
const path = require("path");
const ReactDynamicCssPlugin = require("react-dynamic-css-plugin");
module.exports = {
target: "web",
entry: {
main: "./src/index.jsx"
},
output: {
path: path.join(__dirname, "build"),
filename: `js/[name].min.js`,
chunkFilename: "js/[name].min.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
resolve: {
extensions: [".js", ".jsx"]
},
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"]
}
}
},
{
test: /\.(css)$/,
use: [
{
loader: "css-loader"
}
]
}
]
},
plugins: [
new ReactDynamicCssPlugin({
enabled: true,
entryName: "main",
localIdentName: "myPrefix_[md4:hash:base64:5]",
attributes: /^(class)$/,
exclusionTags: /(path)/i,
exclusionValues: /^(css|sc|icon)-/i,
scope: ""
})
]
};
Options
- enabled | Boolean | Default: true | If false, the plugin will not run
- entryName | String | Default: undefined | The name of the entry point to inject the plugin. If undefined will default to the first entry
- localIdentName | String | Default: "[md4:hash:base64:5]" | The format of the generated class names as [(algorithm):hash:(digest):(length)]
- attributes | RegExp | Default: /^(class)$/ | Regex for HTML attribute names to transform their value
- exclusionTags | RegExp | Default: /(path)/i | Regex for HTML tag names to exclude from transformations
- exclusionValues | RegExp | Default: /^(css|sc|icon)-/i | Regex for HTML attribute values to exclude from transformations
- scope | String | Default: "" | Prefixes the window.setAttributeDynamic method with the scope string
Note: The exclusionValues default excludes class names with the following prefixes. This is because they are commonly generated by other libraries and should not be transformed.
- "css-" which is the emotion default
- "sc-" which is the styled-components default
- "icon-" which is the the standard for icon classes
Mechanism
- The plugin sets localIdentName and getLocalIdent in the css-loader options
- The plugin replaces setAttribute in react-dom with a custom function that transforms the class names at runtime
- The plugin injects the custom setAttributeDynamic function into the entry point of the bundle