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
Rollup minify classnames
Asked Answered
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>
@Sam, thank you for the response. Will this trick work with Sveltekit? –
Styx
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'],
}),
© 2022 - 2024 — McMap. All rights reserved.
autoModules: true
assumes your style files are named likesomething.module.scss
If the do not have.module.
in your style file names, for examplemy-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