1

I configured on my React webpack CSS Loader and Style Loader to obfuscate classNames when a CSS module is loaded.

Although the generated obfuscated className seems too long, I'd like to know if there is a parameter or something I can change on my configuration (webpack) to limit the className size.

ClassName example: _2BzySvHGRXbDRB3RRdNEOO

Webpack code:

{ 
  test: /\.css$/,
  use: [
    {
      loader: 'style-loader'
    },
    {
      loader: 'css-loader',
      options: {
        modules: true,
        importLoaders: 1,
        localsConvention: 'dashes'
      }
    }
  ]
}
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
user ct
  • 47
  • 6

1 Answers1

1

You can use localIdentName to manipulate the CSS fields.

e.g.

{
        test: /\.css$/i,
        loader: 'css-loader',
        options: {
          modules: {
            mode: 'local',
            exportGlobals: true,
            localIdentName: '[path][name]__[local]--[hash:base64:5]',
            context: path.resolve(__dirname, 'src'),
            hashPrefix: 'my-custom-hash',
          },
        },
      },

This may not work depending on your webpack version:

What worked for the user: ref:https://github.com/rails/webpacker/issues/2197

{ test: /\.css$/, 
  use: [ 
   { loader: 'style-loader' }, 
   { loader: 'css-loader', 
        options: { 
          modules: true, 
          importLoaders: 2, 
          localsConvention: 'dashes', 
          modules: { localIdentName: '[hash:base64:5]', 
}, 
} 
} 
] 
},

if you remove the hash from the end, or just use the hash, you'll significantly reduce the class name length. or you can write a custom function in its place to reduce it.

ref: https://github.com/webpack-contrib/css-loader#localidentname

ref: Modify output of localIdentName / getLocalIdent

Danyal
  • 860
  • 7
  • 13
  • 1
    it gives this error: ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'localIdentName'. These properties are valid: object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? } – user ct Jun 06 '20 at 19:10
  • 1
    turns out it works this way, its solved! thanks. { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true, importLoaders: 2, localsConvention: 'dashes', modules: { localIdentName: '[hash:base64:5]', }, } } ] }, – user ct Jun 06 '20 at 19:13
  • 1
    Yeah, I was just looking at that. There's a github issue on this resolution. I'll link it in my reply. Cheers! – Danyal Jun 06 '20 at 19:14