Core CSS parsing functionality that converts CSS source code into detailed Abstract Syntax Trees with configurable parsing levels and error recovery.
Parses CSS source code into an Abstract Syntax Tree with configurable options for parsing context, detail level, and position tracking.
/**
* Parses CSS source code into an Abstract Syntax Tree
* @param css - CSS source code to parse
* @param options - Optional parsing configuration
* @returns Root AST node
*/
function parse(css: string, options?: ParseOptions): CssNode;
interface ParseOptions {
/** Parsing context that determines what type of CSS construct to expect */
context?: 'stylesheet' | 'atrule' | 'atrulePrelude' | 'mediaQueryList' | 'mediaQuery' | 'rule' | 'selectorList' | 'selector' | 'block' | 'declarationList' | 'declaration' | 'value';
/** Name of at-rule when context is 'atrule' or 'atrulePrelude' */
atrule?: string;
/** Property name when context is 'value' */
property?: string;
/** Whether to include position information in AST nodes */
positions?: boolean;
/** Filename for source map generation */
filename?: string;
/** Starting character offset */
offset?: number;
/** Starting line number */
line?: number;
/** Starting column number */
column?: number;
/** Whether to parse at-rule preludes into components */
parseAtrulePrelude?: boolean;
/** Whether to parse rule preludes (selectors) into components */
parseRulePrelude?: boolean;
/** Whether to parse declaration values into components */
parseValue?: boolean;
/** Whether to parse custom property values */
parseCustomProperty?: boolean;
}
interface CssNode {
/** Node type identifier */
type: string;
/** Source location information (if positions: true) */
loc?: SourceLocation;
/** Child nodes (for container nodes) */
children?: List<CssNode>;
/** Additional properties specific to node type */
[key: string]: any;
}
interface SourceLocation {
/** Source filename */
source?: string;
/** Starting position */
start: Position;
/** Ending position */
end: Position;
}
interface Position {
/** Character offset from start of source */
offset: number;
/** Line number (1-based) */
line: number;
/** Column number (1-based) */
column: number;
}Usage Examples:
import { parse } from 'css-tree';
// Basic stylesheet parsing
const ast = parse(`
.example {
color: red;
margin: 10px 0;
}
`);
// Parse specific contexts
const selectorAst = parse('.example > .child', { context: 'selector' });
const valueAst = parse('10px solid red', { context: 'value' });
const declarationAst = parse('color: red', { context: 'declaration' });
// Parse with position tracking
const astWithPositions = parse('.example { color: red; }', {
positions: true,
filename: 'styles.css'
});
// Parse declaration value for specific property
const borderValue = parse('1px solid red', {
context: 'value',
property: 'border'
});
// Parse at-rule prelude
const mediaQuery = parse('screen and (min-width: 768px)', {
context: 'atrulePrelude',
atrule: 'media'
});Different parsing contexts allow parsing specific CSS constructs:
type ParseContext =
| 'stylesheet' // Complete CSS stylesheet (default)
| 'atrule' // At-rule including prelude and block
| 'atrulePrelude' // At-rule prelude only (e.g., media query)
| 'mediaQueryList' // Media query list
| 'mediaQuery' // Single media query
| 'rule' // CSS rule including selector and declarations
| 'selectorList' // Comma-separated selector list
| 'selector' // Single selector
| 'block' // Declaration block
| 'declarationList' // List of declarations
| 'declaration' // Single declaration
| 'value'; // Declaration valueCSS Tree follows W3C error recovery specifications, wrapping unparseable content in Raw nodes rather than throwing errors:
// Parse CSS with syntax errors
const ast = parse('.example { color: red; invalid-property; }');
// Raw nodes preserve unparseable content for later processing
csstree.walk(ast, (node) => {
if (node.type === 'Raw') {
console.log('Unparseable content:', node.value);
}
});The parser generates various node types representing different CSS constructs:
// Common node types
type NodeType =
| 'AnPlusB'
| 'Atrule'
| 'AtrulePrelude'
| 'AttributeSelector'
| 'Block'
| 'Brackets'
| 'CDC'
| 'CDO'
| 'ClassSelector'
| 'Combinator'
| 'Comment'
| 'Declaration'
| 'DeclarationList'
| 'Dimension'
| 'Function'
| 'Hash'
| 'Identifier'
| 'IdSelector'
| 'MediaFeature'
| 'MediaQuery'
| 'MediaQueryList'
| 'Nth'
| 'Number'
| 'Operator'
| 'Parentheses'
| 'Percentage'
| 'PseudoClassSelector'
| 'PseudoElementSelector'
| 'Raw'
| 'Rule'
| 'Selector'
| 'SelectorList'
| 'String'
| 'StyleSheet'
| 'TypeSelector'
| 'UnicodeRange'
| 'Url'
| 'Value'
| 'WhiteSpace';// Minimal parsing for performance
const simpleAst = parse(css, {
parseRulePrelude: false,
parseValue: false
});
// Maximum detail parsing
const detailedAst = parse(css, {
positions: true,
parseAtrulePrelude: true,
parseRulePrelude: true,
parseValue: true,
parseCustomProperty: true
});
// Context-specific parsing
const queries = parse('screen, print', { context: 'mediaQueryList' });
const selector = parse('.example:hover', { context: 'selector' });
const value = parse('calc(100% - 20px)', { context: 'value' });