Socket
Socket
Sign inDemoInstall

css-tree

Package Overview
Dependencies
2
Maintainers
2
Versions
55
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    css-tree

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


Version published
Maintainers
2
Install size
2.33 MB
Created

Package description

What is css-tree?

The css-tree npm package is a tool for parsing and manipulating CSS. It allows users to parse CSS strings into an abstract syntax tree (AST), walk over nodes in the tree, generate CSS strings, and more. It is useful for tasks such as CSS minification, linting, and transformation.

What are css-tree's main functionalities?

Parsing CSS to AST

This feature allows you to parse a CSS string and convert it into an abstract syntax tree (AST) for further manipulation or analysis.

const csstree = require('css-tree');
const ast = csstree.parse('.example { color: red; }');

Walking the AST

This feature enables you to traverse the AST and apply functions or extract information from specific nodes.

csstree.walk(ast, function(node) {
  if (node.type === 'ClassSelector') {
    console.log(node.name);
  }
});

Generating CSS from AST

After manipulating the AST, you can generate a CSS string from the modified AST, which can be used in stylesheets or injected into web pages.

const modifiedAST = csstree.parse('.example { color: blue; }');
const css = csstree.generate(modifiedAST);

Minifying CSS

css-tree can be used to minify CSS by parsing it with compression options and then translating the AST back to a CSS string.

const compressedCSS = csstree.translate(csstree.parse('.example { color: red; }', { compress: true }));

Other packages similar to css-tree

Changelog

Source

2.0.0 (December 3, 2021)

  • Package
    • Dropped support for Node.js prior 14.16 (following patch versions changed it to ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0)
    • Converted to ES modules. However, CommonJS is supported as well (dual module)
    • Added exports for standalone parts instead of internal paths usage (use as import * as parser from "css-tree/parser" or require("css-tree/parser")):
      • css-tree/tokenizer
      • css-tree/parser
      • css-tree/walker
      • css-tree/generator
      • css-tree/lexer
      • css-tree/definition-syntax
      • css-tree/utils
    • Changed bundle set to provide dist/csstree.js (an IIFE version with csstree as a global name) and dist/csstree.esm.js (as ES module). Both are minified
    • Bumped mdn-data to 2.0.23
  • Tokenizer
    • Changed tokenize() to take a function as second argument, which will be called for every token. No stream instance is creating when second argument is ommited.
    • Changed TokenStream#getRawLength() to take second parameter as a function (rule) that check a char code to stop a scanning
    • Added TokenStream#forEachToken(fn) method
    • Removed TokenStream#skipWS() method
    • Removed TokenStream#getTokenLength() method
  • Parser
    • Moved SyntaxError (custom parser's error class) from root of public API to parser via parse.SyntaxError
    • Removed parseError field in parser's SyntaxError
    • Changed selector parsing to produce { type: 'Combinator', name: ' ' } node instead of WhiteSpace node
    • Removed producing of WhiteSpace nodes with the single exception for a custom property declaration with a single white space token as a value
    • Parser adds a whitespace to + and - operators, when a whitespace is before and/or after an operator
    • Exposed parser's inner configuration as parse.config
    • Added consumeUntilBalanceEnd(), consumeUntilLeftCurlyBracket(), consumeUntilLeftCurlyBracketOrSemicolon(), consumeUntilExclamationMarkOrSemicolon() and consumeUntilSemicolonIncluded() methods to parser's inner API to use with Raw instead of Raw.mode
    • Changed Nth to always consume of clause when presented, so it became more general and moves validation to lexer
    • Changed String node type to store decoded string value, i.e. with no quotes and escape sequences
    • Changed Url node type to store decoded url value as a string instead of String or Raw node, i.e. with no quotes, escape sequences and url() wrapper
  • Generator
    • Generator is now determines itself when a white space required between emitting tokens
    • Changed chunk() handler to token() (output a single token) and tokenize() (split a string into tokens and output each of them)
    • Added mode option for generate() to specify a mode of token separation: spec or safe (by default)
    • Added emit(token, type, auto) handler as implementation specific token processor
    • Changed Nth to serialize +n as n
    • Added auto-encoding for a string and url tokens on serialization
  • Lexer
    • Removed Lexer#matchDeclaration() method
  • Utils
    • Added ident, string and url helpers to decode/encode corresponding values, e.g. url.decode('url("image.jpg")') === 'image.jpg'
    • List
      • Changed List to be iterable (iterates data)
      • Changed List#first, List#last and List#isEmpty to getters
      • Changed List#getSize() method to List#size getter
      • Removed List#each() and List#eachRight() methods, List#forEach() and List#forEachRight() should be used instead

Readme

Source

CSSTree logo

CSSTree

NPM version Build Status Coverage Status NPM Downloads Twitter

CSSTree is 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 main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.

Features

  • Detailed parsing with an adjustable level of detail

    By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see AST format for all possible node types). The parsing detail level can be changed through parser options, for example, you can disable parsing of selectors or declaration values for component parts.

  • Tolerant to errors by design

    Parser behaves as spec says: "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (Raw) that allows processing it later.

  • Fast and efficient

    CSSTree is created with focus on performance and effective memory consumption. Therefore it's one of the fastest CSS parsers at the moment.

  • Syntax validation

    The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses mdn/data as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future.

Projects using CSSTree

  • Svelte – Cybernetically enhanced web apps
  • SVGO – Node.js tool for optimizing SVG files
  • CSSO – CSS minifier with structural optimizations
  • NativeScript – NativeScript empowers you to access native APIs from JavaScript directly
  • react-native-svg – SVG library for React Native, React Native Web, and plain React web projects
  • penthouse – Critical Path CSS Generator
  • Bit – Bit is the platform for collaborating on components
  • and more...

Documentation

Tools

Usage

Install with npm:

npm install css-tree

Basic usage:

import * as csstree from 'css-tree';

// parse CSS to AST
const ast = csstree.parse('.example { world: "!" }');

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

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

Syntax matching:

// parse CSS to AST as a declaration value
const ast = csstree.parse('red 1px solid', { context: 'value' });

// match to syntax of `border` property
const matchResult = csstree.lexer.matchProperty('border', ast);

// check first value node is a <color>
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' } ]

Exports

Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations.

import * as tokenizer from 'css-tree/tokenizer';
import * as parser from 'css-tree/parser';
import * as walker from 'css-tree/walker';
import * as lexer from 'css-tree/lexer';
import * as definitionSyntax from 'css-tree/definition-syntax';
import * as utils from 'css-tree/utils';

Using in a browser

There are bundles are available for using in a browser:

  • dist/csstree.js – minified IIFE with csstree as global
<script src="node_modules/css-tree/dist/csstreejs"></script>
<script>
  csstree.parse('.example { color: green }');
</script>
  • dist/csstree.esm.js – minified ES module
<script type="module">
  import { parse } from 'node_modules/css-tree/dist/csstree.esm.js'
  parse('.example { color: green }');
</script>

One of CDN services like unpkg or jsDelivr can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified:

<!-- ESM -->
<script type="module">
  import * as csstree from 'https://cdn.jsdelivr.net/npm/css-tree';
  import * as csstree from 'https://unpkg.com/css-tree';
</script>

<!-- IIFE with an export to global -->
<script src="https://cdn.jsdelivr.net/npm/css-tree/dist/csstree.js"></script>
<script src="https://unpkg.com/css-tree/dist/csstree.js"></script>

Top level API

API map

License

MIT

Keywords

FAQs

Last updated on 03 Dec 2021

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc