CSSTree logo

CSSTree

NPM version Build Status Coverage Status NPM Downloads Twitter

CSSTree is a tool set to work with CSS, including fast detailed parser (string->AST), walker (AST traversal), generator (AST->string) and lexer (validation and matching) based on knowledge of spec and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.

NOTE: The project is in alpha stage since some parts need further improvements, AST format and API are subjects to change. However it’s stable enough and used by packages like CSSO (CSS minifier) and SVGO (SVG optimizer) in production.

Features

Docs

Tools

Related projects

Usage

Install with npm:

```

npm install css-tree ```

Basic usage:

```js var csstree = require(‘css-tree’);

// parse CSS to AST var ast = csstree.parse(‘.example { world: “!” }’);

// traverse AST and modify it csstree.walk(ast, function(node) { if (node.type === ‘ClassSelector’ && node.name === ‘example’) { node.name = ‘hello’; } });

// generate CSS from AST console.log(csstree.generate(ast)); // .hello{world:“!”} ```

Syntax matching:

```js // parse CSS to AST as a declaration value var ast = csstree.parse(‘red 1px solid’, { context: ‘value’ });

// march to syntax of border property var matchResult = csstree.lexer.matchProperty(‘border’, ast);

// check first value node is a console.log(matchResult.isType(ast.children.first(), ‘color’)); // true

// get a type list matched to a node console.log(matchResult.getTrace(ast.children.first())); // [ { type: ‘Property’, name: ‘border’ }, // { type: ‘Type’, name: ‘color’ }, // { type: ‘Type’, name: ‘named-color’ }, // { type: ‘Keyword’, name: ‘red’ } ] ```

Top level API

API map

License

MIT