{"name":"postcss-modules","version":"8.1.0","keywords":["postcss","css","postcss-plugin","modules","css modules","components"],"author":{"name":"Alexander Madyankin","email":"alexander@madyankin.name"},"license":"MIT","_id":"postcss-modules@8.1.0","maintainers":[{"name":"outpunk","email":"alexander@madyankin.name"}],"homepage":"https://github.com/css-modules/postcss-modules#readme","bugs":{"url":"https://github.com/css-modules/postcss-modules/issues"},"dist":{"shasum":"455e34ada32d8c24cd94d0488c5a81e1d1c42f4b","tarball":"http://registry-npm.ywwl.com/postcss-modules/download/postcss-modules-8.1.0.tgz","fileCount":18,"integrity":"sha512-wxaTuHFdaS7J3qXVwjFnjuomSjqqlK3fFSFIR3rbVnpidZDFB2aOXeJTBo6Zygo6hR88jtZ5ecJVS3ZWNe+A4A==","signatures":[{"sig":"MEQCIG4qA2bwTeXsnv1k7NQhIUL2NRNBtwWvnk2b71hvKnNxAiAdO9eGbLEdgwLAHYX/j24lraNYrhCe/qtyWVbt+HeSrA==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":38827,"size":11642,"noattachment":false,"key":"/postcss-modules/-/postcss-modules-8.1.0.tgz"},"main":"build/index.js","types":"index.d.ts","engines":{"node":">=20"},"gitHead":"a6bb9ae9b5ae31cc663a5308aafe61b27db6f99c","scripts":{"test":"make test","prepare":"husky || true"},"_npmUser":{"name":"outpunk","email":"alexander@madyankin.name"},"overrides":{"glob":"^12.0.0","file-type":"^22.0.0"},"repository":{"url":"git+https://github.com/css-modules/postcss-modules.git","type":"git"},"_npmVersion":"11.12.1","description":"PostCSS plugin to use CSS Modules everywhere","directories":{},"lint-staged":{"*.js":["prettier --write","eslint --fix"],"*.{json,md}":["prettier --write"]},"_nodeVersion":"26.0.0","dependencies":{"icss-utils":"^5.1.0","string-hash":"^1.1.3","generic-names":"^4.0.0","lodash.camelcase":"^4.3.0","postcss-modules-scope":"^3.2.1","postcss-modules-values":"^4.0.0","postcss-modules-extract-imports":"^3.1.0","postcss-modules-local-by-default":"^4.2.0"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^30.4.2","husky":"^9.1.7","eslint":"^9.39.0","globals":"^17.7.0","postcss":"^8.5.16","@swc/cli":"^0.8.1","prettier":"^3.9.4","@swc/core":"^1.15.43","@swc/jest":"^0.2.39","@eslint/js":"^9.39.4","lint-staged":"^17.0.8","autoprefixer":"^10.5.2","eslint-plugin-jest":"^29.15.4","eslint-plugin-import":"^2.32.0"},"peerDependencies":{"postcss":"^8.0.0"},"_npmOperationalInternal":{"tmp":"tmp/postcss-modules_8.1.0_1782826548354_0.8656293172913616","host":"s3://npm-registry-packages-npm-production"},"readme":"# postcss-modules\n\nA [PostCSS] plugin to use [CSS Modules] everywhere. Not only at the client side.\n\n[postcss]: https://github.com/postcss/postcss\n[css modules]: https://github.com/css-modules/css-modules\n\n## What is this?\n\nFor example, you have the following CSS:\n\n```css\n/* styles.css */\n:global .page {\n\tpadding: 20px;\n}\n\n.title {\n\tcomposes: title from \"./mixins.css\";\n\tcolor: green;\n}\n\n.article {\n\tfont-size: 16px;\n}\n\n/* mixins.css */\n.title {\n\tcolor: black;\n\tfont-size: 40px;\n}\n\n.title:hover {\n\tcolor: red;\n}\n```\n\nAfter the transformation it will become like this:\n\n```css\n._title_116zl_1 {\n\tcolor: black;\n\tfont-size: 40px;\n}\n\n._title_116zl_1:hover {\n\tcolor: red;\n}\n\n.page {\n\tpadding: 20px;\n}\n\n._title_xkpkl_5 {\n\tcolor: green;\n}\n\n._article_xkpkl_10 {\n\tfont-size: 16px;\n}\n```\n\nAnd the plugin will give you a JSON object for transformed classes:\n\n```json\n{\n\t\"title\": \"_title_xkpkl_5 _title_116zl_1\",\n\t\"article\": \"_article_xkpkl_10\"\n}\n```\n\n## Usage\n\n### Saving exported classes\n\nBy default, a JSON file with exported classes will be placed next to corresponding CSS.\nBut you have a freedom to make everything you want with exported classes, just\nuse the `getJSON` callback. For example, save data about classes into a corresponding JSON file:\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tgetJSON: function (cssFileName, json, outputFileName) {\n\t\t\tvar path = require(\"path\");\n\t\t\tvar cssName = path.basename(cssFileName, \".css\");\n\t\t\tvar jsonFileName = path.resolve(\"./build/\" + cssName + \".json\");\n\t\t\tfs.writeFileSync(jsonFileName, JSON.stringify(json));\n\t\t},\n\t}),\n]);\n```\n\n`getJSON` may also return a `Promise`.\n\n## Using with JavaScript imports\n\n### With a bundler\n\n`import styles from \"./x.css\"` is already supported by every major bundler — they invoke postcss-modules (or its building blocks) under the hood:\n\n- **webpack** — [`css-loader`](https://github.com/webpack-contrib/css-loader) with `{ modules: true }`\n- **Vite** — built-in, files named `*.module.css`\n- **esbuild** — [`esbuild-css-modules-plugin`](https://github.com/indooorsman/esbuild-css-modules-plugin)\n- **Rollup** — [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss) with `modules: true`\n\n### Without a bundler (SSR, Node scripts, Jest/Vitest in node mode)\n\n`postcss-modules` ships a Node [module-customization hook](https://nodejs.org/api/module.html#customization-hooks) 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.\n\n```sh\nnode --import postcss-modules/loader app.mjs\n```\n\n```js\n// app.mjs\nimport styles from \"./button.css\";\n\nconst el = document.createElement(\"div\");\nel.className = styles.primary; // \"_button__primary_xkpkl_5\"\n```\n\nComposing across files (`composes: foo from \"./other.css\"`) works without extra configuration — the same `FileSystemLoader` the PostCSS plugin uses resolves siblings.\n\n#### Configuring the loader\n\nThe hook accepts the same options object as the PostCSS plugin\n(`generateScopedName`, `localsConvention`, `scopeBehaviour`, `globalModulePaths`, `exportGlobals`, `hashPrefix`, `Loader`, `resolve`, `root`). Options are discovered, in priority order:\n\n1. `process.env.POSTCSS_MODULES_CONFIG` — absolute or cwd-relative path to a config file.\n2. `postcss-modules.config.{js,cjs,mjs}` in `process.cwd()`.\n3. A `\"postcss-modules\"` key in the nearest `package.json`.\n4. Empty defaults.\n\nExample config file:\n\n```js\n// postcss-modules.config.cjs\nmodule.exports = {\n\tgenerateScopedName: \"[name]__[local]___[hash:base64:5]\",\n\tlocalsConvention: \"camelCaseOnly\",\n};\n```\n\nOr inline in `package.json`:\n\n```json\n{\n\t\"postcss-modules\": {\n\t\t\"generateScopedName\": \"[name]__[local]___[hash:base64:5]\"\n\t}\n}\n```\n\nOr via an environment variable, useful for per-environment overrides:\n\n```sh\nPOSTCSS_MODULES_CONFIG=./config/css-modules.cjs node --import postcss-modules/loader app.mjs\n```\n\n#### Jest / Vitest\n\nBoth runners accept the same `--import` flag through their Node options.\n\n```sh\nNODE_OPTIONS=\"--import postcss-modules/loader\" jest\nNODE_OPTIONS=\"--import postcss-modules/loader\" vitest\n```\n\nOr wire it into a setup file. The loader runs once per worker, so spawned worker pools (Jest's default) pick it up automatically.\n\n#### TypeScript\n\nAdd an ambient declaration so the compiler accepts default-importing a `.css` file:\n\n```ts\n// css-modules.d.ts\ndeclare module \"*.css\" {\n\tconst tokens: { readonly [key: string]: string };\n\texport default tokens;\n}\n```\n\n#### Limitations\n\n- **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`.\n- **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.\n- **No HMR, no watch mode** — by design. Use a bundler for those.\n- **Node ≥ 20.6.** `module.register` stabilized there.\n\n### Generating scoped names\n\nBy default, the plugin assumes that all the classes are local. You can change\nthis behaviour using the `scopeBehaviour` option:\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tscopeBehaviour: \"global\", // can be 'global' or 'local',\n\t}),\n]);\n```\n\nTo define paths for global modules, use the `globalModulePaths` option.\nIt is an array with regular expressions defining the paths:\n\n```js\npostcss([\n  require('postcss-modules')({\n    globalModulePaths: [/path\\/to\\/legacy-styles/, /another\\/paths/],\n  });\n]);\n```\n\nTo generate custom classes, use the `generateScopedName` callback:\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tgenerateScopedName: function (name, filename, css) {\n\t\t\tvar path = require(\"path\");\n\t\t\tvar i = css.indexOf(\".\" + name);\n\t\t\tvar line = css.substr(0, i).split(/[\\r\\n]/).length;\n\t\t\tvar file = path.basename(filename, \".css\");\n\n\t\t\treturn \"_\" + file + \"_\" + line + \"_\" + name;\n\t\t},\n\t}),\n]);\n```\n\nOr just pass an interpolated string to the `generateScopedName` option\n(More details [here](https://github.com/webpack/loader-utils#interpolatename)):\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tgenerateScopedName: \"[name]__[local]___[hash:base64:5]\",\n\t}),\n]);\n```\n\nIt's possible to add custom hash to generate more unique classes using the `hashPrefix` option (like in [css-loader](https://webpack.js.org/loaders/css-loader/#hashprefix)):\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tgenerateScopedName: \"[name]__[local]___[hash:base64:5]\",\n\t\thashPrefix: \"prefix\",\n\t}),\n]);\n```\n\n### Exporting globals\n\nIf you need to export global names via the JSON object along with the local ones, add the `exportGlobals` option:\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\texportGlobals: true,\n\t}),\n]);\n```\n\n### Loading source files\n\nIf you need, you can pass a custom loader (see [FileSystemLoader] for example):\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tLoader: CustomLoader,\n\t}),\n]);\n```\n\nYou can also pass any needed root path:\n\n```js\npostcss([\n  require('postcss-modules')({\n    root: 'C:\\\\',\n  });\n]);\n```\n\n### localsConvention\n\nType: `String | (originalClassName: string, generatedClassName: string, inputFile: string) => string | string[]`\nDefault: `null`\n\nStyle of exported classnames, the keys in your json.\n\n|         Name          |    Type    | Description                                                                                      |\n| :-------------------: | :--------: | :----------------------------------------------------------------------------------------------- |\n|   **`'camelCase'`**   | `{String}` | Class names will be camelized, the original class name will not to be removed from the locals    |\n| **`'camelCaseOnly'`** | `{String}` | Class names will be camelized, the original class name will be removed from the locals           |\n|    **`'dashes'`**     | `{String}` | Only dashes in class names will be camelized                                                     |\n|  **`'dashesOnly'`**   | `{String}` | Dashes in class names will be camelized, the original class name will be removed from the locals |\n|      **`'all'`**      | `{String}` | Emit the original class name plus the camelCase and dashes-camelCase variants                    |\n|     **`'none'`**      | `{String}` | Emit only the original class name (equivalent to leaving `localsConvention` unset)               |\n\nFor an input class `foo-bar` resolving to scoped name `_a`:\n\n| Mode            | Emitted locals                                                                              |\n| --------------- | ------------------------------------------------------------------------------------------- |\n| `camelCase`     | `{ \"foo-bar\": \"_a\", \"fooBar\": \"_a\" }`                                                       |\n| `camelCaseOnly` | `{ \"fooBar\": \"_a\" }`                                                                        |\n| `dashes`        | `{ \"foo-bar\": \"_a\", \"fooBar\": \"_a\" }`                                                       |\n| `dashesOnly`    | `{ \"fooBar\": \"_a\" }`                                                                        |\n| `all`           | `{ \"foo-bar\": \"_a\", \"fooBar\": \"_a\" }` (camelCase + dashesCamelCase collapse for this input) |\n| `none`          | `{ \"foo-bar\": \"_a\" }`                                                                       |\n\nIn lieu of a string, a custom function can generate the exported class names. The function may return either a single string or an array of strings; when an array is returned every entry is added to the locals map and resolves to the same value:\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n\t\tlocalsConvention: (original, generated) => [original, generated, original.toUpperCase()],\n\t}),\n]);\n// .foo-bar { ... }  →  { \"foo-bar\": \"_a\", \"_a\": \"_a\", \"FOO-BAR\": \"_a\" }\n```\n\n### Resolve path alias\n\nYou can rewrite paths for `composes/from` by using the `resolve` option.\nIt's useful when you need to resolve custom path alias.\n\nParameters:\n\n- `file` — a module we want to resolve\n- `importer` — the file that imports the module we want to resolve\n\nReturn value: `string | null | Promise<string | null>`\n\n```js\npostcss([\n\trequire(\"postcss-modules\")({\n    \tresolve: function (file, importer) {\n\t\t\treturn path.resolve(\n\t\t\t\tpath.dirname(importer),\n\t\t\t\tfile.replace(/^@/, process.cwd()\n\t\t\t);\n    \t},\n  \t}),\n]);\n```\n\n## Integration with templates\n\nThe plugin only transforms CSS classes to CSS modules.\nBut you probably want to integrate these CSS modules with your templates.\nHere are some examples.\n\nAssume you've saved project's CSS modules in `cssModules.json`:\n\n```json\n{\n\t\"title\": \"_title_xkpkl_5 _title_116zl_1\",\n\t\"article\": \"_article_xkpkl_10\"\n}\n```\n\n### Pug (ex-Jade)\n\nLet's say you have a Pug template `about.jade`:\n\n```jade\nh1(class=css.title) postcss-modules\narticle(class=css.article) A PostCSS plugin to use CSS Modules everywhere\n```\n\nRender it:\n\n```js\nvar jade = require(\"jade\");\nvar cssModules = require(\"./cssModules.json\");\nvar html = jade.compileFile(\"about.jade\")({ css: cssModules });\nconsole.log(html);\n```\n\nAnd you'll get the following HTML:\n\n```html\n<h1 class=\"_title_xkpkl_5 _title_116zl_1\">postcss-modules</h1>\n<article class=\"_article_xkpkl_10\">A PostCSS plugin to use CSS Modules everywhere</article>\n```\n\n### HTML\n\nFor HTML transformation we'll use [PostHTML](https://github.com/posthtml/posthtml) and [PostHTML CSS Modules](https://github.com/maltsev/posthtml-css-modules):\n\n```bash\nnpm install --save posthtml posthtml-css-modules\n```\n\nHere is our template `about.html`:\n\n```html\n<h1 css-module=\"title\">postcss-modules</h1>\n<article css-module=\"article\">A PostCSS plugin to use CSS Modules everywhere</article>\n```\n\nTransform it:\n\n```js\nvar fs = require(\"fs\");\nvar posthtml = require(\"posthtml\");\nvar posthtmlCssModules = require(\"posthtml-css-modules\");\nvar template = fs.readFileSync(\"./about.html\", \"utf8\");\n\nposthtml([posthtmlCssModules(\"./cssModules.json\")])\n\t.process(template)\n\t.then(function (result) {\n\t\tconsole.log(result.html);\n\t});\n```\n\n(for using other build systems please check [the documentation of PostHTML](https://github.com/posthtml/posthtml/blob/master/readme.md))\n\nAnd you'll get the following HTML:\n\n```html\n<h1 class=\"_title_xkpkl_5 _title_116zl_1\">postcss-modules</h1>\n<article class=\"_article_xkpkl_10\">A PostCSS plugin to use CSS Modules everywhere</article>\n```\n\n## May I see the plugin in action?\n\nSure! Take a look at the [example](https://github.com/outpunk/postcss-modules-example).\n\nSee [PostCSS] docs for examples for your environment and don't forget to run\n\n```\nnpm install --save-dev postcss postcss-modules\n```\n\n[filesystemloader]: https://github.com/css-modules/css-modules-loader-core/blob/master/src/file-system-loader.js\n\n## Sponsors\n\n- Dmitry Olyenyov\n","publish_time":1782826548486,"_cnpm_publish_time":1782826548486,"dist-tags":{"latest":"9.0.1"}}