
Security News
The Changelog Podcast: Practical Steps to Stay Safe on npm
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.

Fast detailed CSS parser
Work in progress. Project in alpha stage since AST format is subject to change.
Docs and tools:
Related projects:
> npm install css-tree
var csstree = require('css-tree');
csstree.walk(csstree.parse('.a { color: red; }'), function(node) {
console.log(node.type);
});
// StyleSheet
// Rule
// SelectorList
// Selector
// Class
// Block
// Declaration
// Value
// Identifier
Parses CSS to AST.
NOTE: Currenly parser omits redundant separators, spaces and comments (except exclamation comments, i.e.
/*! comment */) on AST build.
Options:
context String β parsing context, useful when some part of CSS is parsing (see below)atrule String β make sense for atruleExpression context to apply some atrule specific parse rulesproperty String β make sense for value context to apply some property specific parse rulespositions Boolean β should AST contains node position or not, store data in info property of nodes (false by default)filename String β filename of source that adds to info when positions is true, uses for source map generation (<unknown> by default)line Number β initial line number, useful when parse fragment of CSS to compute correct positionscolumn Number β initial column number, useful when parse fragment of CSS to compute correct positionsContexts:
stylesheet (default) β regular stylesheet, should be suitable in most casesatrule β at-rule (e.g. @media screen, print { ... })atruleExpression β at-rule expression (screen, print for example above)rule β rule (e.g. .foo, .bar:hover { color: red; border: 1px solid black; })selectorList β selector group (.foo, .bar:hover for rule example)selector β selector (.foo or .bar:hover for rule example)block β block with curly braces ({ color: red; border: 1px solid black; } for rule example)declarationList β block content w/o curly braces (color: red; border: 1px solid black; for rule example), useful to parse HTML style attribute valuedeclaration β declaration (color: red or border: 1px solid black for rule example)value β declaration value (red or 1px solid black for rule example)// simple parsing with no options
var ast = csstree.parse('.example { color: red }');
// parse with options
var ast = csstree.parse('.foo.bar', {
context: 'simpleSelector',
positions: true
});
Make an AST node deep copy.
var orig = csstree.parse('.test { color: red }');
var copy = csstree.clone(orig);
csstree.walk(copy, function(node) {
if (node.type === 'Class') {
node.name = 'replaced';
}
});
console.log(csstree.translate(orig));
// .test{color:red}
console.log(csstree.translate(copy));
// .replaced{color:red}
Converts AST to string.
var ast = csstree.parse('.test { color: red }');
console.log(csstree.translate(ast));
// > .test{color:red}
The same as translate() but also generates source map (nodes should contain positions in info property).
var ast = csstree.parse('.test { color: red }', {
filename: 'my.css',
positions: true
});
console.log(csstree.translateWithSourceMap(ast));
// { css: '.test{color:red}', map: SourceMapGenerator {} }
Visits each node of AST in natural way and calls handler for each one. handler receives three arguments:
node β current AST nodeitem β node wrapper when node is a list member; this wrapper contains references to prev and next nodes in listlist β reference to list when node is a list member; it's useful for operations on list like remove() or insert()Context for handler an object, that contains references to some parent nodes:
root β refers to ast root node (actually it's a node passed to walker function)stylesheet β refers to StyleSheet node, usually it's a root nodeatruleExpression β refers to AtruleExpression node if anyrule β refers to closest Rule node if anyselector β refers to SelectorList node if anyblock - refers to closest Block node if anydeclaration β refers to Declaration node if anyfunction β refers to closest Function, PseudoClass or PseudoElement node if current node inside one of them// collect all urls in declarations
var csstree = require('./lib/index.js');
var urls = [];
var ast = csstree.parse(`
@import url(import.css);
.foo { background: url('foo.jpg'); }
.bar { background-image: url(bar.png); }
`);
csstree.walk(ast, function(node) {
if (this.declaration !== null && node.type === 'Url') {
var value = node.value;
if (value.type === 'Raw') {
urls.push(value.value);
} else {
urls.push(value.value.substr(1, value.value.length - 2));
}
}
});
console.log(urls);
// [ 'foo.jpg', 'bar.png' ]
Same as walk() but visits nodes in down-to-top order. Useful to process deepest nodes and then their parents.
var csstree = require('css-tree');
var ast = csstree.parse('.a { color: red; }');
csstree.walk(ast, function(node) {
console.log(node.type);
});
// StyleSheet
// Rule
// SelectorList
// Selector
// Class
// Block
// Declaration
// Value
// Identifier
csstree.walkUp(ast, function(node) {
console.log(node.type);
});
// Class
// Selector
// SelectorList
// Identifier
// Value
// Declaration
// Block
// Rule
// StyleSheet
Same as walk() but visits Rule and Atrule nodes only.
Same as walkRules() but visits nodes in reverse order (from last to first).
Visit all declarations.
MIT
Syntax matching use mdn/data by Mozilla Contributors
PostCSS is a tool for transforming CSS with JavaScript plugins. It can do similar tasks as css-tree, such as parsing, walking the AST, and generating CSS. PostCSS is plugin-based, which makes it more extensible and allows for a wide range of transformations.
Sass is a preprocessor scripting language that is interpreted or compiled into CSS. It offers more syntactic features compared to css-tree, such as variables, nesting, and mixins, but it is not primarily focused on parsing and manipulating existing CSS.
Less is another CSS pre-processor, similar to Sass, that extends the capabilities of CSS with dynamic behavior such as variables, mixins, operations, and functions. Less and css-tree serve different purposes, with Less focusing on writing CSS in a more functional way and css-tree on parsing and manipulation.
clean-css is a fast and efficient CSS optimizer for Node.js and the browser. It focuses on minification, which is one of the features of css-tree, but does not provide a general-purpose CSS parsing and manipulation API.
FAQs
A tool set for CSS: fast detailed parser (CSS β AST), walker (AST traversal), generator (AST β CSS) and lexer (validation and matching) based on specs and browser implementations
The npm package css-tree receives a total of 36,032,899 weekly downloads. As such, css-tree popularity was classified as popular.
We found that css-tree demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.

Security News
Experts push back on new claims about AI-driven ransomware, warning that hype and sponsored research are distorting how the threat is understood.

Security News
Ruby's creator Matz assumes control of RubyGems and Bundler repositories while former maintainers agree to step back and transfer all rights to end the dispute.