{"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.","language":"javascript","status":"maintenance","last_verified":"Sun Apr 19","install":{"commands":["npm install postcss-modules-parser"],"cli":null},"imports":["const Parser = require('postcss-modules-parser');"],"auth":{"required":false,"env_vars":[]},"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`.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}