Registry / serialization / postcss-selector-parser

postcss-selector-parser

JSON →
library7.1.1jsnpmunverified

postcss-selector-parser is a utility library designed to parse CSS selector strings into an abstract syntax tree (AST), providing a structured API for inspecting and manipulating these selectors. It is an integral tool within the PostCSS ecosystem, enabling advanced selector transformations, linting, and optimizations by allowing plugins to programmatically interact with selector structures. The current stable version is 7.1.1, with a release cadence that responds to feature demands and bug fixes within the broader PostCSS community. Its key differentiators include a robust AST representation, comprehensive traversal methods (like `walk`), and support for both synchronous and asynchronous processing, making it highly flexible for various build environments. It also includes full TypeScript type definitions to enhance developer experience and ensure type safety.

npm install postcss-selector-parser
INSTALL
IMPORT
SIG · POSTCSS-SELECTOR-P
P
postcss-selector-parser
serializationjavascriptv7.1.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
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.

parser
import parser from 'postcss-selector-parser';
const parser = require('postcss-selector-parser');
While the README shows CommonJS `require`, ESM `import` is the idiomatic way in modern Node.js and TypeScript projects. The package provides a default export.
Root, Selector, Node
import { Root, Selector, Node } from 'postcss-selector-parser';
import { RootNode, SelectorNode } from 'postcss-selector-parser';
Core AST node types are named `Root`, `Selector`, `Node`, etc., not suffixed with `Node` in the import.
Node types for TypeScript
import type { Root, Selector, Node, Combinator } from 'postcss-selector-parser';
When only importing types, use `import type` for clarity and better tree-shaking in TypeScript.

Demonstrates how to parse and transform CSS selectors using `postcss-selector-parser`, showcasing both synchronous and asynchronous API usage and node traversal.

import parser from 'postcss-selector-parser'; // This example demonstrates parsing a CSS selector string into an AST, // traversing its nodes, and performing a simple transformation by // converting all element selectors to uppercase. It also shows both // synchronous and asynchronous processing. async function processSelectors() { const transform = (selectors: parser.Root) => { selectors.walkTags((tag) => { // Example transformation: convert all tag names to uppercase tag.value = tag.value.toUpperCase(); console.log(`Transformed tag: ${tag.value}`); }); selectors.walkCombinators((combinator) => { console.log(`Found combinator: '${combinator.value}'`); }); }; // Synchronous processing example const originalSyncSelector = 'div > p.foo, a:hover'; console.log(`Original (sync): ${originalSyncSelector}`); const transformedSync = parser(transform).processSync(originalSyncSelector); console.log(`Transformed (sync): ${transformedSync}\n`); // Expected: DIV > P.foo, A:hover // Asynchronous processing example const originalAsyncSelector = 'h1 + h2[data-test]'; console.log(`Original (async): ${originalAsyncSelector}`); const transformedAsync = await parser(transform).process(originalAsyncSelector); console.log(`Transformed (async): ${transformedAsync}`); // Expected: H1 + H2[data-test] } processSelectors().catch(console.error);
Debug
Known issues
breakingVersion 7.0.0 introduced a significant change by making insertions during iteration safe. This implies that any custom transformations or modifications to the selector AST while iterating over its nodes might behave differently or require adjustments to ensure proper handling of new or removed nodes during traversal.
fix
Review existing code that modifies the selector AST during `walk` or `each` iterations. Ensure that insertions/deletions are handled correctly in the new safe iteration context, potentially re-evaluating node indices or references if directly manipulated.
affects: >=7.0.0
gotchaThe `process` and `processSync` methods accept an optional `lossless` option (defaulting to `true`) which controls whether original whitespace and comments are preserved. If you expect normalized, compact selector output (e.g., `h1,h2,h3` instead of `h1, h2, h3`), you must explicitly set `lossless: false`.
fix
To normalize whitespace and remove comments from the output selector string, pass `{ lossless: false }` as the second argument to `parser().process()` or `parser().processSync()`.
affects: >=6.0.0
gotchaAlthough `postcss-selector-parser` is written for Node.js and the `README` traditionally shows CommonJS `require()`, modern JavaScript projects, especially those using TypeScript or recent Node.js versions, typically use ESM `import` statements. Using `require()` in an ESM-only module will lead to errors.
fix
For modern projects, use `import parser from 'postcss-selector-parser';`. If you are in a CommonJS environment, `const parser = require('postcss-selector-parser');` remains valid.
affects: >=6.0.0
Errors
Common errors & fixes
TypeError: parser is not a function
Attempting to call `parser` as a constructor (e.g., `new parser()`) or trying to use it directly without invoking it first as a factory function to get the actual processor instance.
fix
The main export is a factory function that returns a processor. Call it as `parser(transformFunction)` or `parser()` to get the processing instance, then call `process` or `processSync` on that instance. Example: `parser(transform).processSync(...)` or `parser().processSync(...)`.
ReferenceError: require is not defined
Attempting to use `require()` syntax in an ECMAScript Module (ESM) context (e.g., in a file with `"type": "module"` in `package.json` or a `.mjs` file).
fix
Change your import statement from `const parser = require('postcss-selector-parser');` to `import parser from 'postcss-selector-parser';`.
SyntaxError: Unexpected token 'export'
Trying to import a CommonJS-style module using `import` syntax when the environment or bundler is not configured to handle interop correctly, or when the `postcss-selector-parser` package's `package.json` doesn't properly define its exports for ESM.
fix
Ensure your project's `tsconfig.json` (for TypeScript) or build tool (e.g., Webpack, Rollup) is configured to handle `moduleResolution: 'bundler'` or `node` correctly. Verify that Node.js version is recent enough to support `package.json` `exports` map if applicable. For older setups, consider a CommonJS build or adjusting bundler config.
Upgrade
Version history
7.1.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
postcss-selector-parser — npm install postcss-selector-parser · libregistry