postcss-modules
PostCSS plugin to use CSS Modules everywhere
A PostCSS plugin that automatically renames CSS class names to be unique, preventing style conflicts and generating a JSON map to look up the renamed classes in your templates.
Plain-English Explanation
This plugin solves a common problem in web development: CSS class name conflicts. When you write CSS for different parts of your website, it's easy for class names to accidentally clash—for example, two components both using .title will interfere with each other. CSS Modules is a system that automatically renames your classes to be unique, so .title becomes something like _title_xkpkl_5. This plugin brings that automatic renaming to PostCSS, a popular tool for processing CSS files.
Here's what it does in practice. You write normal CSS with regular class names, and the plugin rewrites those names to be unique by adding hashes and file information. At the same time, it creates a JSON file that maps your original class names to the new renamed ones. So when you refer to "title" in your template code, you look it up in that JSON file to find out it's now called _title_xkpkl_5, and you use that in your HTML. The plugin handles all the renaming automatically—you don't have to manually track or manage the new names.
The plugin gives you a lot of flexibility in how it works. You can customize how the new class names are generated (whether they're based on the filename, a hash, line numbers, or your own formula). You can mark certain CSS as "global" so it doesn't get renamed. You can choose whether class names in the JSON should be camelCased (like myClassName instead of my-class-name). And you can intercept the JSON output to save it wherever you want or process it however you need.
This is particularly useful for teams building server-side rendered websites, modular component libraries, or any project where you want to isolate CSS to prevent conflicts but still need to reference those styles from your HTML templates. The README includes examples of using the output with template languages like Pug and PostHTML, showing how to plug the renamed class names into your markup automatically.
Where it fits
- Automatically rename CSS classes to unique names so components stop clashing over shared class names.
- Generate a JSON map from original class names to renamed ones for use in HTML templates.
- Mark specific CSS rules as global so they skip the automatic renaming.
- Build server-side rendered sites with isolated, conflict-free component styles.