Registry / serialization / postcss-modules-parser

postcss-modules-parser

JSON →
library1.1.1jsnpmunverified

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.

serialization
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

This package is primarily CommonJS. For ESM environments, use `require()` or ensure your bundler/runtime correctly handles CJS interop.

const Parser = require('postcss-modules-parser');

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`.

const postcss = require('postcss'); const Parser = require('postcss-modules-parser'); const path = require('path'); // Mock CSS content for demonstration const mainCssContent = ` .myClass { color: red; } :local(.anotherClass) { font-size: 16px; } @value primaryColor from './colors.css'; .container { background-color: primaryColor; } `; const colorsCssContent = ` @value primaryColor: #f00; `; /** * A fetch function that simulates loading content and returns mock tokens. * In a real PostCSS Modules setup, this function would typically be provided * by a higher-level plugin (e.g., `postcss-modules`) to handle imported files. * @param {string} filePath The path to the file to fetch. * @param {string} importer The path of the file importing `filePath`. * @param {number} iteration Current iteration counter (since 1.1.0) * @return {object|Promise<object>} Tokens or a Promise resolving to tokens */ function mockFetch(filePath, importer, iteration) { console.log(`[mockFetch] Fetching "${filePath}" imported by "${importer}" (iteration: ${iteration})`); let tokens = {}; if (path.basename(filePath) === 'colors.css') { // Simulate what a real CSS Modules loader would do: process this file and return its tokens tokens = { 'primaryColor': '#f00' // Manually define tokens for simplicity }; } else { // This fetch should primarily be called for `@value` imports by the parser. console.warn(`[mockFetch] Unexpected file path requested: ${filePath}`); return Promise.reject(new Error(`File not found: ${filePath}`)); } return Promise.resolve(tokens); } async function runParserExample() { const absolutePathToMainCss = path.resolve(__dirname, 'style.css'); // Create a PostCSS root node from the main CSS content const root = postcss.parse(mainCssContent, { from: absolutePathToMainCss }); // Instantiate the parser with the mock fetch function const parser = new Parser({ fetch: mockFetch }); // Create a mock PostCSS result object (needed by parser.parse) const mockResult = { opts: { from: absolutePathToMainCss, to: absolutePathToMainCss }, root: root, messages: [], warn: (msg) => console.warn(`PostCSS Warning: ${msg}`), error: (msg) => console.error(`PostCSS Error: ${msg}`) }; try { // Call the parser's parse method. This method mutates the `root` object, // adding `root.tokens` after resolving `@value` imports. await parser.parse(root, mockResult, {}); console.log('\n--- Final Output ---'); console.log('Resolved PostCSS Root Tokens (after @value resolution):'); console.log(root.tokens); /* Expected simplified output for root.tokens (might vary based on full integration): { myClass: 'myClass', anotherClass: 'anotherClass', container: 'container', primaryColor: '#f00' // resolved from colors.css } */ } catch (error) { console.error('Error during PostCSS Modules parsing:', error); } } runParserExample();
Debug
Known footguns
gotchaThe `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.
gotcha`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.
gotchaThis 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.
Upgrade
Version history

Breaking-change detection hasn't run for this library yet.

Audit
Security & dependencies

CVE tracking and dependency tree are planned for a later release.

Agent activity
13 hits · last 30 days
gptbot
4
ahrefsbot
4
amazonbot
4
script
1
Resources