I'd like to minify my classnames (for very minimal source protection purposes) in both my output CSS files and in the rendered JSX from my React components similarly to this Webpack plugin: https://github.com/vreshch/optimize-css-classnames-plugin
Is there any existing option I can use to achieve this, either Webpack or otherwise? Thanks very much.
From:
<div className="long-class-name"></div>
.long-class-name {
}
To:
<div class="a"></div>
.a {
}
As you're already using Webpack, I think one good option is to use CSS Modules to accomplish that. You can use either css-loader or postcss-modules to do that, for example.
Basically, by using CSS Modules, you can import
your CSS and treat it as a JSON. So, if you write .long-class-name { }
you'll have something like this { 'long-class-name': '<<interpolated name>>' }
. The trick here is that the <<interpolated name>>
in my example is something you can set programmaticaly.
Webpack has some predefined tokens that you can use, as you can see here: https://github.com/webpack/loader-utils#interpolatename. And you can check an example here:
{
test: /\.css$/,
use: [
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}
]
}
However, if you want something more "customized", you can specify a getLocalIdent
function:
{
test: /\.css$/,
use: [
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
getLocalIdent: (context, localIdentName, localName, options) => {
return 'whatever_random_class_name';
}
}
}
]
}
Please, refer to the docs to read more about the options on CSS Modules
.
Doing this way, you can specify your class names the way you need and solve your problem.
Hope that helps!
For anyone wanting to easily mangle classnames in Next.js, use my package!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With