Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify/Mangle CSS Classnames in JSX and CSS output from Webpack (or other programmatic means)

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 {
}
like image 398
Slbox Avatar asked Feb 14 '18 18:02

Slbox


2 Answers

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!

like image 87
William Martins Avatar answered Sep 19 '22 23:09

William Martins


For anyone wanting to easily mangle classnames in Next.js, use my package!

like image 39
Ken Mueller Avatar answered Sep 20 '22 23:09

Ken Mueller