8

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 {
}
3

2 Answers 2

11

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Hey @Slbox, did it help you?
I didn't end up pursuing this, but this answer should theoretically work.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.