postcss-modules 8.3.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,23 @@
1
1
  # Changelog
2
2
 
3
- ## 8.2.0
3
+ ## 9.0.0
4
+
5
+ ### Breaking
6
+
7
+ - Minimum Node.js bumped from 20 to 20.6, the release that stabilized `module.register`.
8
+
9
+ ### Added
10
+
11
+ - New `postcss-modules/loader` subpath — an opt-in Node module-customization hook. Run with `node --import postcss-modules/loader app.mjs` and JavaScript files can do `import styles from "./button.css"` to receive the class-name token map as the default export, mirroring `css-loader`'s `modules` workflow. Options live in `postcss-modules.config.{js,cjs,mjs}` in cwd, the `POSTCSS_MODULES_CONFIG` env var, or a `"postcss-modules"` key in `package.json`, and accept the same shape as the PostCSS plugin. Aimed at non-bundler use cases (SSR, Node scripts, Jest/Vitest in node mode); bundler users keep using their existing integrations. [#80](https://github.com/madyankin/postcss-modules/issues/80)
12
+
13
+ ## 8.3.1
14
+
15
+ ### Fixed
16
+
17
+ - `hashPrefix` is now applied when no custom `generateScopedName` is set. Previously the option was only honoured by `generic-names`, so the built-in default generator silently ignored it. [#160](https://github.com/madyankin/postcss-modules/issues/160)
18
+ - Empty rules left behind after `:global { ... }` unwrapping (e.g. a Sass block containing only a multi-line comment) are now removed instead of emitted as orphaned `{ ... }` blocks. [#136](https://github.com/madyankin/postcss-modules/issues/136)
19
+
20
+ ## 8.3.0
4
21
 
5
22
  ### Added
6
23
 
package/README.md CHANGED
@@ -92,6 +92,101 @@ postcss([
92
92
 
93
93
  `getJSON` may also return a `Promise`.
94
94
 
95
+ ## Using with JavaScript imports
96
+
97
+ ### With a bundler
98
+
99
+ `import styles from "./x.css"` is already supported by every major bundler — they invoke postcss-modules (or its building blocks) under the hood:
100
+
101
+ - **webpack** — [`css-loader`](https://github.com/webpack-contrib/css-loader) with `{ modules: true }`
102
+ - **Vite** — built-in, files named `*.module.css`
103
+ - **esbuild** — [`esbuild-css-modules-plugin`](https://github.com/indooorsman/esbuild-css-modules-plugin)
104
+ - **Rollup** — [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss) with `modules: true`
105
+
106
+ ### Without a bundler (SSR, Node scripts, Jest/Vitest in node mode)
107
+
108
+ `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.
109
+
110
+ ```sh
111
+ node --import postcss-modules/loader app.mjs
112
+ ```
113
+
114
+ ```js
115
+ // app.mjs
116
+ import styles from "./button.css";
117
+
118
+ const el = document.createElement("div");
119
+ el.className = styles.primary; // "_button__primary_xkpkl_5"
120
+ ```
121
+
122
+ Composing across files (`composes: foo from "./other.css"`) works without extra configuration — the same `FileSystemLoader` the PostCSS plugin uses resolves siblings.
123
+
124
+ #### Configuring the loader
125
+
126
+ The hook accepts the same options object as the PostCSS plugin
127
+ (`generateScopedName`, `localsConvention`, `scopeBehaviour`, `globalModulePaths`, `exportGlobals`, `hashPrefix`, `Loader`, `resolve`, `root`). Options are discovered, in priority order:
128
+
129
+ 1. `process.env.POSTCSS_MODULES_CONFIG` — absolute or cwd-relative path to a config file.
130
+ 2. `postcss-modules.config.{js,cjs,mjs}` in `process.cwd()`.
131
+ 3. A `"postcss-modules"` key in the nearest `package.json`.
132
+ 4. Empty defaults.
133
+
134
+ Example config file:
135
+
136
+ ```js
137
+ // postcss-modules.config.cjs
138
+ module.exports = {
139
+ generateScopedName: "[name]__[local]___[hash:base64:5]",
140
+ localsConvention: "camelCaseOnly",
141
+ };
142
+ ```
143
+
144
+ Or inline in `package.json`:
145
+
146
+ ```json
147
+ {
148
+ "postcss-modules": {
149
+ "generateScopedName": "[name]__[local]___[hash:base64:5]"
150
+ }
151
+ }
152
+ ```
153
+
154
+ Or via an environment variable, useful for per-environment overrides:
155
+
156
+ ```sh
157
+ POSTCSS_MODULES_CONFIG=./config/css-modules.cjs node --import postcss-modules/loader app.mjs
158
+ ```
159
+
160
+ #### Jest / Vitest
161
+
162
+ Both runners accept the same `--import` flag through their Node options.
163
+
164
+ ```sh
165
+ NODE_OPTIONS="--import postcss-modules/loader" jest
166
+ NODE_OPTIONS="--import postcss-modules/loader" vitest
167
+ ```
168
+
169
+ Or wire it into a setup file. The loader runs once per worker, so spawned worker pools (Jest's default) pick it up automatically.
170
+
171
+ #### TypeScript
172
+
173
+ Add an ambient declaration so the compiler accepts default-importing a `.css` file:
174
+
175
+ ```ts
176
+ // css-modules.d.ts
177
+ declare module "*.css" {
178
+ const tokens: { readonly [key: string]: string };
179
+ export default tokens;
180
+ }
181
+ ```
182
+
183
+ #### Limitations
184
+
185
+ - **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`.
186
+ - **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.
187
+ - **No HMR, no watch mode** — by design. Use a bundler for those.
188
+ - **Node ≥ 20.6.** `module.register` stabilized there.
189
+
95
190
  ### Generating scoped names
96
191
 
97
192
  By default, the plugin assumes that all the classes are local. You can change
@@ -0,0 +1,43 @@
1
+ import { existsSync } from "fs";
2
+ import { readFile } from "fs/promises";
3
+ import path from "path";
4
+ import { pathToFileURL } from "url";
5
+
6
+ const CONFIG_NAMES = [
7
+ "postcss-modules.config.js",
8
+ "postcss-modules.config.cjs",
9
+ "postcss-modules.config.mjs",
10
+ ];
11
+
12
+ async function importConfig(filePath) {
13
+ const url = pathToFileURL(filePath).href;
14
+ const mod = await import(url);
15
+ return mod.default || mod;
16
+ }
17
+
18
+ export async function loadConfig(cwd = process.cwd()) {
19
+ const explicit = process.env.POSTCSS_MODULES_CONFIG;
20
+ if (explicit) {
21
+ const resolved = path.isAbsolute(explicit) ? explicit : path.resolve(cwd, explicit);
22
+ return importConfig(resolved);
23
+ }
24
+
25
+ for (const name of CONFIG_NAMES) {
26
+ const candidate = path.resolve(cwd, name);
27
+ if (existsSync(candidate)) {
28
+ return importConfig(candidate);
29
+ }
30
+ }
31
+
32
+ const pkgPath = path.resolve(cwd, "package.json");
33
+ if (existsSync(pkgPath)) {
34
+ try {
35
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
36
+ if (pkg["postcss-modules"]) return pkg["postcss-modules"];
37
+ } catch {
38
+ // ignore unreadable / malformed package.json
39
+ }
40
+ }
41
+
42
+ return {};
43
+ }
@@ -0,0 +1,3 @@
1
+ import { register } from "node:module";
2
+
3
+ register("./loaderHooks.mjs", import.meta.url);
@@ -0,0 +1,25 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { fileURLToPath } from "node:url";
3
+ import { processCSS } from "./processCSS.js";
4
+ import { loadConfig } from "./loadConfig.mjs";
5
+
6
+ let configPromise;
7
+ function getConfig() {
8
+ if (!configPromise) configPromise = loadConfig();
9
+ return configPromise;
10
+ }
11
+
12
+ export async function load(url, context, nextLoad) {
13
+ if (!url.startsWith("file:") || !url.endsWith(".css")) {
14
+ return nextLoad(url, context);
15
+ }
16
+ const filename = fileURLToPath(url);
17
+ const source = await readFile(filename, "utf8");
18
+ const opts = await getConfig();
19
+ const tokens = await processCSS(source, filename, opts);
20
+ return {
21
+ format: "module",
22
+ source: `export default ${JSON.stringify(tokens)};\n`,
23
+ shortCircuit: true,
24
+ };
25
+ }
@@ -77,6 +77,11 @@ function makePlugin(opts) {
77
77
  ]).process(css, {
78
78
  from: inputFile
79
79
  });
80
+ // Remove rules whose selector was reduced to whitespace after
81
+ // `:global { ... }` unwrapping — see #136.
82
+ css.walkRules((rule)=>{
83
+ if (rule.selector.trim() === "") rule.remove();
84
+ });
80
85
  const out = loader.finalSource;
81
86
  if (out) css.prepend(out);
82
87
  if (opts.localsConvention) {
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "processCSS", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return processCSS;
9
+ }
10
+ });
11
+ const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss"));
12
+ const _fs = require("fs");
13
+ const _fs1 = require("./fs");
14
+ const _pluginFactory = require("./pluginFactory");
15
+ function _interop_require_default(obj) {
16
+ return obj && obj.__esModule ? obj : {
17
+ default: obj
18
+ };
19
+ }
20
+ (0, _fs1.setFileSystem)({
21
+ readFile: _fs.readFile,
22
+ writeFile: _fs.writeFile
23
+ });
24
+ async function processCSS(source, filename, opts = {}) {
25
+ let tokens = {};
26
+ const plugin = (0, _pluginFactory.makePlugin)({
27
+ ...opts,
28
+ getJSON: (_cssFile, json)=>{
29
+ tokens = json;
30
+ }
31
+ });
32
+ await (0, _postcss.default)([
33
+ plugin
34
+ ]).process(source, {
35
+ from: filename
36
+ });
37
+ return tokens;
38
+ }
package/build/scoping.js CHANGED
@@ -68,14 +68,16 @@ function isValidBehaviour(behaviour) {
68
68
  function getDefaultScopeBehaviour(scopeBehaviour) {
69
69
  return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
70
70
  }
71
- function generateScopedNameDefault(name, filename, css) {
72
- const i = css.indexOf(`.${name}`);
73
- const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
74
- const hash = (0, _stringhash.default)(css).toString(36).substr(0, 5);
75
- return `_${name}_${hash}_${lineNumber}`;
71
+ function makeDefaultScopedNameGenerator(hashPrefix) {
72
+ return function generateScopedNameDefault(name, filename, css) {
73
+ const i = css.indexOf(`.${name}`);
74
+ const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
75
+ const hash = (0, _stringhash.default)(`${hashPrefix || ""}${css}`).toString(36).substr(0, 5);
76
+ return `_${name}_${hash}_${lineNumber}`;
77
+ };
76
78
  }
77
79
  function getScopedNameGenerator(generateScopedName, hashPrefix) {
78
- const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
80
+ const scopedNameGenerator = generateScopedName || makeDefaultScopedNameGenerator(hashPrefix);
79
81
  if (typeof scopedNameGenerator === "function") {
80
82
  return scopedNameGenerator;
81
83
  }
package/index.d.ts CHANGED
@@ -50,3 +50,5 @@ declare interface PostcssModulesPlugin {
50
50
  declare const PostcssModulesPlugin: PostcssModulesPlugin;
51
51
 
52
52
  export = PostcssModulesPlugin;
53
+
54
+ declare module "postcss-modules/loader" {}
package/package.json CHANGED
@@ -1,9 +1,17 @@
1
1
  {
2
2
  "name": "postcss-modules",
3
- "version": "8.3.0",
3
+ "version": "9.0.0",
4
4
  "description": "PostCSS plugin to use CSS Modules everywhere",
5
5
  "main": "build/index.js",
6
6
  "types": "index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "default": "./build/index.js"
11
+ },
12
+ "./loader": "./build/loader.mjs",
13
+ "./package.json": "./package.json"
14
+ },
7
15
  "keywords": [
8
16
  "postcss",
9
17
  "css",
@@ -48,7 +56,7 @@
48
56
  "prettier": "^3.9.4"
49
57
  },
50
58
  "engines": {
51
- "node": ">=20"
59
+ "node": ">=20.6"
52
60
  },
53
61
  "scripts": {
54
62
  "test": "make test",