Rollup minify classnames
Asked Answered
S

2

5

Is there any rollup.js plugins which allow to obfuscate / mangle CSS class names? I haven't found anything, except this one for webpack: https://github.com/sndyuk/mangle-css-class-webpack-plugin

Styx answered 18/8, 2020 at 5:3 Comment(0)
D
7

This can be achieved with rollup-plugin-postcss. As per the readme, configuration options for the modules property are passed through to postcss-modules. Using the generateScopedName property you're able to set the format of the class name:

generateScopedName: "[hash:base64:8]",

There are more examples in the postcss-modules readme including how to generate the name dynamically. Note that you are responsible for ensuring that the names are unique enough to not clash.

The full rollup config would look something like:

import postcss from "rollup-plugin-postcss";
... // other imports

export default {
  ... // rest of config
  plugins: [
    ... // other plugins
    postcss({
      ...
      modules: {
        generateScopedName: "[hash:base64:8]",
      },
      autoModules: true,
    }),
    ...
  ],
};

Then something like:

.parent {
  display: grid;
  grid-template-rows: auto 1fr auto;
}
/* styles.module.css */
import STYLES from './styles.module.css';

...

// Use the style however
<div className={STYLES.parent}> 
  ...
</div>

Ends up looking like:

.xSgFDOB2 {
  display: grid;
  grid-template-rows: auto 1fr auto;
}
<div class="xSgFDOB2">
  ...
</div>
Delacruz answered 3/1, 2021 at 20:45 Comment(2)
Please note that autoModules: true assumes your style files are named like something.module.scss If the do not have .module. in your style file names, for example my-component.scss, then generatedScopedName fails silently, the class names are not truncated, and "undefined" gets inserted in your compiled javascript. To fix this, set autoModules to false. github.com/egoist/rollup-plugin-postcss/issues/…Veedis
@Sam, thank you for the response. Will this trick work with Sveltekit?Styx
E
0

The solution for me was adding generateScopedName to modules and setting autoModules: false,

    postcss({
        extensions: ['.scss'],
        modules: {
            generateScopedName: `[name]__[local]__[hash:base64:5]`,
        },
        autoModules: false,
        use: ['sass'],
    }),
Exosphere answered 4/4, 2023 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.