CSSTree is a comprehensive toolkit for processing CSS, providing a fast and detailed parser to transform CSS source into an Abstract Syntax Tree (AST), a walker for efficient AST traversal, a generator to serialize AST back into CSS, and a lexer for syntax validation and matching based on W3C specifications and browser implementations. The current stable version is 3.2.1, with frequent patch and minor releases indicating active development. It stands out for its performance (benchmarked as one of the fastest), spec compliance, detailed AST format with adjustable parsing levels, and inherent error tolerance by wrapping malformed content in `Raw` nodes instead of discarding it. It also leverages `mdn/data` for robust syntax validation, making it suitable for complex CSS analysis and source-to-source transformations.
npm install css-treeVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates parsing CSS into an AST, traversing the AST to inspect nodes (e.g., declarations), modifying the AST, and then generating the modified CSS string. It also shows error handling during parsing.
Review AST traversal and manipulation logic to gracefully handle new `AtRule` types introduced in CSS specifications. Use `walk` with `visit` options to target specific node types or ensure `enter`/`leave` handlers are robust to unknown node types.
Refactor any custom logic for handling nested CSS or `@media` inside rules, as CSSTree now natively supports these structures. The AST will reflect `NestingSelector` nodes and altered `DeclarationList` behavior within blocks.
If your code expects `Array` methods on `children` properties of AST nodes (e.g., `node.children.map()`), ensure you pass `{ list: false }` to the `parse()` method: `parse(css, { list: false })`. Otherwise, use `List` methods like `node.children.toArray()` or iterate using `forEach`.When traversing the AST, explicitly check for and handle `Raw` nodes. You can inspect their `value` property for the raw string content. If validation is important, use the `Lexer#validate()` method (enhanced in v3.0.1 with an `errors` array) or implement custom logic to process or report these `Raw` nodes.
Either convert the `List` to an array using `node.children.toArray().map(...)` or set the `list` option to `false` when parsing: `parse(css, { list: false })`.Review the CSS input for missing semicolons, unbalanced curly brackets, or other syntax errors. If using `parse()` with `onParseError`, inspect the `error` object for `line` and `column` to pinpoint the exact location of the issue. The parser is tolerant, so this error is more likely from strict validation or subsequent processing.
Update your AST processing logic (e.g., `walk` callbacks) to recognize and handle new `AtRule` types. You can use a `default` case in a switch statement or `else` clause to log unknown types or skip them gracefully.
No dependency data recorded yet.