CSS Syntax Parser

1.5.1 · active · verified Tue Apr 21

The `css-syntax-parser` package provides a specialized JavaScript and TypeScript library for parsing and interpreting CSS value definition syntax as specified by MDN (Mozilla Developer Network). It generates an Abstract Syntax Tree (AST) that precisely details the structure, combinators, and multipliers present in a given CSS syntax string. Currently stable at version 1.5.1, the library does not specify a fixed release cadence but has seen ongoing development since its initial release. Its core differentiation lies in its precise adherence to the MDN syntax definition, offering programmatic access to the parsed structure including term types (e.g., `keyword`, `data-type`, `composed`), combinators (e.g., `|`, `&&`), and multipliers (e.g., `{1,4}`, `?`). This enables developers to validate, analyze, or generate CSS property values based on their defined grammar, which is a niche but critical use case for tooling and language servers.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a CSS value definition, accessing its properties, and safely type-narrowing the resulting AST nodes in TypeScript.

import { resolveSyntax, Term, TermType, BracketsTerm, ComposedTerm, DataTypeTerm, TermMultiplier } from 'css-syntax-parser';

const syntax: Term = resolveSyntax('[ <length> | <percentage> | auto ]{1,4}');

console.log(`Parsed syntax type: ${syntax.type}`);

if (syntax.type === TermType.BRACKETS) {
    const brackets: BracketsTerm = syntax as BracketsTerm;
    console.log(`Bracket multiplier: ${brackets.multiplier}`);

    if (brackets.multiplier === TermMultiplier.RANGE) {
        console.log(`Range: min=${brackets.range.min}, max=${brackets.range.max}`);
    }

    if (brackets.content.type === TermType.COMPOSED) {
        const content: ComposedTerm = brackets.content as ComposedTerm;
        console.log(`Content type: ${content.type}, combinator: ${content.combinator}`);

        const child1 = content.children[1];
        if (child1.type === TermType.DATA_TYPE) {
            const dataTypeChild: DataTypeTerm = child1 as DataTypeTerm;
            console.log(`Second child: type=${dataTypeChild.type}, name=${dataTypeChild.name}, nonTerminal=${dataTypeChild.nonTerminal}`);
        }
    }
}

view raw JSON →