{"id":13791,"library":"postcss-modules-parser","title":"PostCSS Modules Parser","description":"postcss-modules-parser is a foundational utility designed to extract CSS Modules tokens directly from CSS files. Operating currently at version `1.1.1`, its release cadence appears to be slow, suggesting a stable, mature, and perhaps less actively developed but still functional library. Unlike `postcss-modules` which handles the full compilation pipeline, this package focuses specifically on the parsing aspect, providing a lower-level API for developers who need granular control over token extraction. A key differentiator is its flexibility in supporting both synchronous and asynchronous file loaders via a user-provided `fetch` function, which is responsible for loading CSS content and processing it with a PostCSS instance. This makes it adaptable for various build environments and custom processing workflows, serving as a component within a larger CSS Modules processing setup.","status":"maintenance","version":"1.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/css-modules/postcss-icss","tags":["javascript","css-modules","postcss","css","postcss-plugin"],"install":[{"cmd":"npm install postcss-modules-parser","lang":"bash","label":"npm"},{"cmd":"yarn add postcss-modules-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add postcss-modules-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required to parse CSS content and create a PostCSS root node, which is then processed by this parser. It's a conceptual peer dependency for usage.","package":"postcss","optional":false}],"imports":[{"note":"This package is primarily CommonJS. For ESM environments, use `require()` or ensure your bundler/runtime correctly handles CJS interop.","wrong":"import Parser from 'postcss-modules-parser';\nimport { Parser } from 'postcss-modules-parser';","symbol":"Parser","correct":"const Parser = require('postcss-modules-parser');"}],"quickstart":{"code":"const postcss = require('postcss');\nconst Parser = require('postcss-modules-parser');\nconst path = require('path');\n\n// Mock CSS content for demonstration\nconst mainCssContent = `\n.myClass { color: red; }\n:local(.anotherClass) { font-size: 16px; }\n@value primaryColor from './colors.css';\n.container { background-color: primaryColor; }\n`;\n\nconst colorsCssContent = `\n@value primaryColor: #f00;\n`;\n\n/**\n * A fetch function that simulates loading content and returns mock tokens.\n * In a real PostCSS Modules setup, this function would typically be provided\n * by a higher-level plugin (e.g., `postcss-modules`) to handle imported files.\n * @param  {string} filePath   The path to the file to fetch.\n * @param  {string} importer   The path of the file importing `filePath`.\n * @param  {number} iteration  Current iteration counter (since 1.1.0)\n * @return {object|Promise<object>}      Tokens or a Promise resolving to tokens\n */\nfunction mockFetch(filePath, importer, iteration) {\n  console.log(`[mockFetch] Fetching \"${filePath}\" imported by \"${importer}\" (iteration: ${iteration})`);\n\n  let tokens = {};\n\n  if (path.basename(filePath) === 'colors.css') {\n    // Simulate what a real CSS Modules loader would do: process this file and return its tokens\n    tokens = {\n      'primaryColor': '#f00' // Manually define tokens for simplicity\n    };\n  } else {\n    // This fetch should primarily be called for `@value` imports by the parser.\n    console.warn(`[mockFetch] Unexpected file path requested: ${filePath}`);\n    return Promise.reject(new Error(`File not found: ${filePath}`));\n  }\n\n  return Promise.resolve(tokens);\n}\n\nasync function runParserExample() {\n  const absolutePathToMainCss = path.resolve(__dirname, 'style.css');\n\n  // Create a PostCSS root node from the main CSS content\n  const root = postcss.parse(mainCssContent, { from: absolutePathToMainCss });\n\n  // Instantiate the parser with the mock fetch function\n  const parser = new Parser({ fetch: mockFetch });\n\n  // Create a mock PostCSS result object (needed by parser.parse)\n  const mockResult = {\n    opts: {\n      from: absolutePathToMainCss,\n      to: absolutePathToMainCss\n    },\n    root: root,\n    messages: [],\n    warn: (msg) => console.warn(`PostCSS Warning: ${msg}`),\n    error: (msg) => console.error(`PostCSS Error: ${msg}`)\n  };\n\n  try {\n    // Call the parser's parse method. This method mutates the `root` object,\n    // adding `root.tokens` after resolving `@value` imports.\n    await parser.parse(root, mockResult, {});\n\n    console.log('\\n--- Final Output ---');\n    console.log('Resolved PostCSS Root Tokens (after @value resolution):');\n    console.log(root.tokens);\n    /* Expected simplified output for root.tokens (might vary based on full integration):\n    {\n      myClass: 'myClass',\n      anotherClass: 'anotherClass',\n      container: 'container',\n      primaryColor: '#f00' // resolved from colors.css\n    }\n    */\n  } catch (error) {\n    console.error('Error during PostCSS Modules parsing:', error);\n  }\n}\n\nrunParserExample();","lang":"javascript","description":"This example demonstrates how `postcss-modules-parser` is instantiated and used within a PostCSS processing pipeline. It shows defining a `fetch` function to handle `@value` imports (simulating resolution of `colors.css`) and then calling `parser.parse()` on a main CSS root node. The parsed tokens, including resolved `@value` imports, are populated onto the PostCSS `root.tokens` object, which would then be consumed by a higher-level plugin like `postcss-modules`."},"warnings":[{"fix":"Remove any logic that strips quotes from values returned by your `fetch` function.","message":"The `fetch` function API was updated in version `1.1.0`. It no longer requires manually removing quotes from the resolved values. Code written for older versions might perform unnecessary quote stripping.","severity":"gotcha","affected_versions":">=1.1.0"},{"fix":"Consider using `postcss-modules` if you need a complete CSS Modules solution. If using `postcss-modules-parser` directly, ensure you correctly construct and pass PostCSS `root` and `result` objects.","message":"`postcss-modules-parser` is typically used as an internal component within other PostCSS plugins (like `postcss-modules`) rather than directly by end-users. Its `parser.parse()` method expects a PostCSS `root` node and `result` object, making direct standalone usage require more boilerplate.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `const Parser = require('postcss-modules-parser');` in Node.js. For ESM projects, configure your build tool (e.g., Webpack, Rollup, esbuild) to correctly handle CommonJS dependencies or ensure Node.js compatibility layers are active.","message":"This package appears to be CommonJS-only, which can lead to issues in modern ESM-only Node.js projects or browser environments without proper transpilation/bundling. Direct `import` statements for `postcss-modules-parser` will likely fail without specific configuration.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'1.1.1':26 'activ':41 'adapt':118 'api':70 'appear':30 'aspect':64 'asynchron':91 'build':121 'cadenc':29 'compil':55 'compon':130 'content':107 'control':76 'css':15,20,106,134,140,143 'css-modul':139 'current':23 'custom':124 'design':12 'develop':42,72 'differenti':82 'direct':18 'environ':122 'extract':14,79 'fetch':99 'file':21,92 'flexibl':85 'focus':59 'foundat':10 'full':54 'function':45,100 'granular':75 'handl':52 'instanc':114 'javascript':138 'key':81 'larger':133 'less':40 'level':69 'librari':46 'load':105 'loader':93 'lower':68 'lower-level':67 'make':116 'matur':37 'modul':2,6,16,50,135,141 'need':74 'oper':22 'packag':58 'pars':63 'parser':3,7 'perhap':39 'pipelin':56 'plugin':146 'postcss':1,5,49,113,142,145 'postcss-modul':48 'postcss-modules-pars':4 'postcss-plugin':144 'process':109,125,136 'provid':65,98 'releas':28 'respons':103 'serv':127 'setup':137 'slow':33 'specif':60 'stabl':36 'still':44 'suggest':34 'support':87 'synchron':89 'token':17,78 'unlik':47 'user':97 'user-provid':96 'util':11 'various':120 'version':25 'via':94 'within':131 'workflow':126","created_at":"2026-04-20T01:56:19.706552+00:00","updated_at":"2026-04-20T01:56:19.706552+00:00","problems":[{"fix":"Ensure you are using `const Parser = require('postcss-modules-parser');` for CommonJS environments.","cause":"Attempting to use `new Parser()` when the `Parser` object was not correctly imported as a constructor, often due to incorrect ESM import syntax for a CJS module.","error":"TypeError: Parser is not a constructor"},{"fix":"Provide a `fetch` function in the constructor options: `new Parser({ fetch: myFetchFunction })`.","cause":"The `fetch` option was omitted when instantiating `postcss-modules-parser`.","error":"Error: `fetch` function is not provided"},{"fix":"Review your `fetch` function implementation to ensure it correctly resolves file paths and returns the expected token object (or a Promise resolving to it). Ensure all `@value` dependencies are resolvable by your `fetch` function.","cause":"The `fetch` function, which is responsible for resolving imported files (e.g., from `@value` statements), returned a rejected Promise or threw an error because it couldn't find or process the requested file.","error":"UnhandledPromiseRejectionWarning: Error: File not found: ..."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/css-modules/postcss-icss","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/postcss-modules-parser","openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}