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.

npm install postcss-modules-parser
INSTALL
IMPORT
SIG · POSTCSS-MODULES-PA
P
postcss-modules-parser
serializationjavascriptv1.1.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
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 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

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

Parser
✓ const Parser = require('postcss-modules-parser');
✗ import Parser from 'postcss-modules-parser'; import { Parser } from 'postcss-modules-parser';
This package is primarily CommonJS. For ESM environments, use `require()` or ensure your bundler/runtime correctly handles CJS interop.

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 issues
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.
fix
Remove any logic that strips quotes from values returned by your `fetch` function.
affects: >=1.1.0
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.
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.
affects: >=1.0.0
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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Parser is not a constructor
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.
fix
Ensure you are using `const Parser = require('postcss-modules-parser');` for CommonJS environments.
Error: `fetch` function is not provided
The `fetch` option was omitted when instantiating `postcss-modules-parser`.
fix
Provide a `fetch` function in the constructor options: `new Parser({ fetch: myFetchFunction })`.
UnhandledPromiseRejectionWarning: Error: File not found: ...
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.
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.
Upgrade
Version history
1.1.1latest on npm
Audit
Dependencies
postcssrequiredRequired 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.
Agent activity
9 hits · last 30 days
node
8
Amazon
1
Resources
postcss-modules-parser — npm install postcss-modules-parser · libregistry