vite-plugin-optimize-css-modules

raw JSON →
1.4.0 verified Mon Apr 27 auth: no javascript

A Vite plugin that minifies CSS modules classnames in production builds by replacing long generated hashes with the shortest possible identifiers (a, b, c, ...). v1.4.0, actively maintained, supports Vite v2–v8. Reduces CSS file size by up to 30% and build time by up to 94% (benchmarked on Bootstrap and Materialize). Ships TypeScript types. Alternative to generic CSS minifiers because it targets classname mangling specifically for CSS modules, preserving functionality while maximizing compression.

error TypeError: optimizeCssModules is not a function
cause Using default import instead of named import.
fix
Change to: import { optimizeCssModules } from 'vite-plugin-optimize-css-modules'
error Error: Vite plugin 'optimizeCssModules' requires a valid 'vite' peer dependency.
cause Missing or incompatible Vite version.
fix
Install Vite v2–v8: npm install vite@^5.0.0 (or matching your project's needs)
error CSS classnames not minified in production build
cause The plugin is not added to Vite config or CSS file is not a CSS module (missing `.module.css` extension).
fix
Add optimizeCssModules() to the plugins array in vite.config.ts and ensure your CSS file is named like styles.module.css.
gotcha Only works with CSS modules: files ending with `.module.css` (or configured identically). Do not expect it to minify global CSS classnames.
fix Ensure your CSS files use the `.module.css` extension or configure Vite's `css.modules` option properly.
gotcha Production-only transformation: The plugin only transforms CSS during `vite build`, not in dev mode (`vite dev`). Classnames appear as original hashes during development.
fix This is by design. No action needed, but be aware that production CSS differs from dev CSS.
breaking Peer dependency version range changed: v1.4.0 supports Vite v2–v8. Previous versions may have different ranges. Ensure your Vite version is compatible.
fix Update Vite to v2, v3, v4, v5, v6, v7, or v8. Check package.json for exact peer range.
gotcha Does not handle dynamic classnames: If you use template literals or concatenation to build classnames, the plugin cannot guarantee correct minification because it only knows about static CSS module imports.
fix Use static class references from CSS modules (e.g., `styles.card`) rather than constructing them from strings.
npm install vite-plugin-optimize-css-modules
yarn add vite-plugin-optimize-css-modules
pnpm add vite-plugin-optimize-css-modules

Add the Vite plugin to your config. No options needed; works out of the box.

// vite.config.ts
import { optimizeCssModules } from 'vite-plugin-optimize-css-modules';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    optimizeCssModules()
  ]
});

// Then run: npx vite build
// Your CSS modules classnames will be minified automatically in production.