Related:
- csstree-validator – NPM package to validate CSS
- stylelint-csstree-validator – plugin for stylelint to validate CSS
- Gulp plugin
- Sublime plugin
- VS Code plugin
- Atom plugin
> npm install css-tree
var csstree = require('css-tree');
csstree.walk(csstree.parse('.a { color: red; }'), function(node) {
console.log(node.type);
});
// Class
// SimpleSelector
// Selector
// Property
// Identifier
// Value
// Declaration
// Block
// Ruleset
// StyleSheetParse CSS to AST.
NOTE: Currenly parser omit redundant separators, spaces and comments (except exclamation comments, i.e.
/*! comment */) on AST build.
Options:
contextString – parsing context, useful when some part of CSS is parsing (see below)propertyString – make sense fordeclarationcontext to apply some property specific parse rulespositionsBoolean – should AST contains node position or not, store data ininfoproperty of nodes (falseby default)filenameString – filename of source that adds to info whenpositionsis true, uses for source map generation (<unknown>by default)lineNumber – initial line number, useful when parse fragment of CSS to compute correct positionscolumnNumber – initial column number, useful when parse fragment of CSS to compute correct positions
Contexts:
stylesheet(default) – regular stylesheet, should be suitable in most casesatrule– at-rule (e.g.@media screen, print { ... })atruleExpression– at-rule expression (screen, printfor example above)ruleset– rule (e.g..foo, .bar:hover { color: red; border: 1px solid black; })selector– selector group (.foo, .bar:hoverfor ruleset example)simpleSelector– selector (.fooor.bar:hoverfor ruleset example)block– block content w/o curly braces (color: red; border: 1px solid black;for ruleset example)declaration– declaration (color: redorborder: 1px solid blackfor ruleset example)value– declaration value (redor1px solid blackfor ruleset 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 {} }Visit all nodes of AST and call handler for each one. handler receives three arguments:
node– current AST nodeitem– node wrapper when node is a list member; this wrapper contains references toprevandnextnodes in listlist– reference to list when node is a list member; it's useful for operations on list likeremove()orinsert()
Context for handler an object, that contains references to some parent nodes:
root– refers toastor root nodestylesheet– refers to closestStyleSheetnode, it may be a top-level or at-rule block stylesheetatruleExpression– refers toAtruleExpressionnode if current node inside at-rule expressionruleset– refers toRulesetnode if current node inside a rulesetselector– refers toSelectornode if current node inside a selectordeclaration– refers toDeclarationnode if current node inside a declarationfunction– refers to closestFunctionorFunctionalPseudonode 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 Ruleset and Atrule nodes only.
Same as walkRules() but visits nodes in reverse order (from last to first).
Visit all declarations.
MIT
Template:CSSData by Mozilla Contributors is licensed under [CC-BY-SA 2.5]