postcss-modules
A PostCSS plugin to use CSS Modules everywhere. Not only at the client side.
What is this?
For example, you have the following CSS:
/* styles.css */
:global .page {
padding: 20px;
}
.title {
composes: title from "./mixins.css";
color: green;
}
.article {
font-size: 16px;
}
/* mixins.css */
.title {
color: black;
font-size: 40px;
}
.title:hover {
color: red;
}
After the transformation it will become like this:
._title_116zl_1 {
color: black;
font-size: 40px;
}
._title_116zl_1:hover {
color: red;
}
.page {
padding: 20px;
}
._title_xkpkl_5 {
color: green;
}
._article_xkpkl_10 {
font-size: 16px;
}
And the plugin will give you a JSON object for transformed classes:
{
"title": "_title_xkpkl_5 _title_116zl_1",
"article": "_article_xkpkl_10"
}
Usage
Saving exported classes
By default, a JSON file with exported classes will be placed next to corresponding CSS.
But you have a freedom to make everything you want with exported classes, just
use the getJSON callback. For example, save data about classes into a corresponding JSON file:
postcss([
require("postcss-modules")({
getJSON: function (cssFileName, json, outputFileName) {
var path = require("path");
var cssName = path.basename(cssFileName, ".css");
var jsonFileName = path.resolve("./build/" + cssName + ".json");
fs.writeFileSync(jsonFileName, JSON.stringify(json));
},
}),
]);
getJSON may also return a Promise.
Using with JavaScript imports
With a bundler
import styles from "./x.css" is already supported by every major bundler โ they invoke postcss-modules (or its building blocks) under the hood:
Without a bundler (SSR, Node scripts, Jest/Vitest in node mode)
postcss-modules ships a Node module-customization hook at the postcss-modules/loader subpath. Register it with --import and any import of a .css file is intercepted, run through the plugin, and exposed as a default-exported token map.
node --import postcss-modules/loader app.mjs
// app.mjs
import styles from "./button.css";
const el = document.createElement("div");
el.className = styles.primary; // "_button__primary_xkpkl_5"
Composing across files (composes: foo from "./other.css") works without extra configuration โ the same FileSystemLoader the PostCSS plugin uses resolves siblings.
Configuring the loader
The hook accepts the same options object as the PostCSS plugin
(generateScopedName, localsConvention, scopeBehaviour, globalModulePaths, exportGlobals, hashPrefix, Loader, resolve, root). Options are discovered, in priority order:
process.env.POSTCSS_MODULES_CONFIG โ absolute or cwd-relative path to a config file.
postcss-modules.config.{js,cjs,mjs} in process.cwd().
- A
"postcss-modules" key in the nearest package.json.
- Empty defaults.
Example config file:
// postcss-modules.config.cjs
module.exports = {
generateScopedName: "[name]__[local]___[hash:base64:5]",
localsConvention: "camelCaseOnly",
};
Or inline in package.json:
{
"postcss-modules": {
"generateScopedName": "[name]__[local]___[hash:base64:5]"
}
}
Or via an environment variable, useful for per-environment overrides:
POSTCSS_MODULES_CONFIG=./config/css-modules.cjs node --import postcss-modules/loader app.mjs
Jest / Vitest
Both runners accept the same --import flag through their Node options.
NODE_OPTIONS="--import postcss-modules/loader" jest
NODE_OPTIONS="--import postcss-modules/loader" vitest
Or wire it into a setup file. The loader runs once per worker, so spawned worker pools (Jest's default) pick it up automatically.
TypeScript
Add an ambient declaration so the compiler accepts default-importing a .css file:
// css-modules.d.ts
declare module "*.css" {
const tokens: { readonly [key: string]: string };
export default tokens;
}
Limitations
- ESM only.
require("./x.css") is not supported; the underlying transform is async and cannot be expressed through require.extensions. Use a .mjs entrypoint, or "type": "module" in package.json.
- Tokens only, no CSS output. The loader returns the class-name map but does not emit the transformed CSS. SSR setups that need the stylesheet should use a bundler or call
postcss([require("postcss-modules")(...)]).process(...) directly to capture both.
- No HMR, no watch mode โ by design. Use a bundler for those.
- Node โฅ 20.6.
module.register stabilized there.
Generating scoped names
By default, the plugin assumes that all the classes are local. You can change
this behaviour using the scopeBehaviour option:
postcss([
require("postcss-modules")({
scopeBehaviour: "global", // can be 'global', 'local' or 'pure',
}),
]);
Like local mode, pure mode localizes class and ID names, but it also requires
every comma-separated selector branch to contain at least one local class or ID.
For example, .button :global(.icon) is allowed, while :global(.page) is
rejected. Add /* cssmodules-pure-ignore */ immediately before a selector or
at-rule to skip this check once, or put
/* cssmodules-pure-no-check */ at the top of a file to disable the check for
the whole file.
To define paths for global modules, use the globalModulePaths option.
It is an array with regular expressions defining the paths. Matching files are
treated as global even when scopeBehaviour is "pure":
postcss([
require('postcss-modules')({
globalModulePaths: [/path\/to\/legacy-styles/, /another\/paths/],
});
]);
To generate custom classes, use the generateScopedName callback:
postcss([
require("postcss-modules")({
generateScopedName: function (name, filename, css) {
var path = require("path");
var i = css.indexOf("." + name);
var line = css.slice(0, i).split(/[\r\n]/).length;
var file = path.basename(filename, ".css");
return "_" + file + "_" + line + "_" + name;
},
}),
]);
Or just pass an interpolated string to the generateScopedName option
(More details here):
postcss([
require("postcss-modules")({
generateScopedName: "[name]__[local]___[hash:base64:5]",
}),
]);
It's possible to add custom hash to generate more unique classes using the hashPrefix option (like in css-loader):
postcss([
require("postcss-modules")({
generateScopedName: "[name]__[local]___[hash:base64:5]",
hashPrefix: "prefix",
}),
]);
Exporting globals
If you need to export global names via the JSON object along with the local ones, add the exportGlobals option:
postcss([
require("postcss-modules")({
exportGlobals: true,
}),
]);
Loading source files
If you need, you can pass a custom loader (see FileSystemLoader for example):