React Standard Tree CSS Selector Parser

2.2.3 · maintenance · verified Tue Apr 21

rst-selector-parser is a JavaScript library designed for parsing CSS-like selectors specifically within the context of React Standard Trees (RST). It provides utilities to parse a CSS selector string into an Abstract Syntax Tree (AST) representing the selector's structure, and conversely, to generate a selector string from such an AST. This package is frequently utilized in conjunction with testing libraries like Enzyme for traversing and querying rendered React components. Currently at version 2.2.3, it is a fork of the `scalpel` library, adapted and optimized for the RST environment, ensuring compatibility with its unique traversal needs. Its primary differentiation lies in this specialized focus, offering a robust and programmatic way to interact with component trees using familiar CSS selector syntax, which can be particularly beneficial for testing and introspection workflows in React applications. The last significant update was in late 2019, suggesting a mature but slow-moving maintenance phase.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a CSS selector into a tokenized AST and then generating a selector string back from the AST.

import { createGenerator, createParser } from 'rst-selector-parser';

const parser = createParser();
const generator = createGenerator();

// Parse a CSS selector string into an AST
const tokens = parser.parse('.foo.bar');
console.log('Parsed Tokens:', JSON.stringify(tokens, null, 2));
/*
[
  {
    "type": "selector",
    "body": [
      {
        "type": "classSelector",
        "name": "foo"
      },
      {
        "type": "classSelector",
        "name": "bar"
      }
    ]
  }
]
*/

// Generate a selector string from the AST
const selector = generator.generate(tokens[0]);
console.log('Generated Selector:', selector);
// .foo.bar

view raw JSON →