This plugin requires vite of v3 or greater. It only makes sense to use if you're using css modules.
$ npm install --save-dev vite-plugin-optimize-css-modules
In your vite.config.ts
simply add the plugin:
import { optimizeCssModules } from 'vite-plugin-optimize-css-modules';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
optimizeCssModules()
]
})
And that's it. When running vite build
your generated CSS should be significantly smaller.
Benchmarks are done against bootstrap and materialize.css assuming all the classes are used as css modules. The benchmark code is located in the benchmarks directory.
Run them by building the plugin via npm run build
and then running npm run benchmarks
.
The results below are from a MacBook Air M2 with node v22.8.0.
Input | Build Time | Gzip Size | Brotli Size |
---|---|---|---|
bootstrap-5.0.2.module.css | 525ms (-94.06% / -8311ms) | 21.3 kB (-26.53% / -7.69 kB) | 21.3 kB (-27.54% / -6 kB) |
materialize-1.0.0.module.css | 572ms (-92.59% / -7156ms) | 20.1 kB (-19.70% / -4.93 kB) | 20.1 kB (-21.33% / -4.3 kB) |
By default, when using css modules, you end up with hashes or other long class-names in your bundled css files:
@keyframes _close-card_pzatx_1 {
/* ...css */
}
._card_pzatx_32 {
/* ...css */
}
._back_pzatx_49 ._content_pzatx_70 ._close_pzatx_74 {
/* ...css */
}
By using this module, the smalles possible classname will be used for each "id":
@keyframes a {
/* ...css */
}
.v {
/* ...css */
}
.c .s .w {
/* ...css */
}