What is postcss-values-parser?
The postcss-values-parser package is a tool for parsing CSS values, allowing developers to analyze and manipulate CSS strings in JavaScript. It provides a detailed AST (Abstract Syntax Tree) for CSS values, making it easier to understand and modify CSS properties programmatically.
What are postcss-values-parser's main functionalities?
Parsing CSS values
This feature allows you to parse any string representing CSS values into a structured AST. The code sample demonstrates parsing a simple CSS value string.
const parse = require('postcss-values-parser').parse;
let root = parse('10px solid black');
console.log(root.nodes);
Walking through the AST
After parsing CSS values into an AST, this feature enables walking through the AST nodes. This can be useful for analyzing or modifying specific parts of the CSS value.
const parse = require('postcss-values-parser').parse;
let root = parse('10px solid black');
root.walk((node) => console.log(node));
Modifying CSS values
This feature demonstrates how to modify CSS values after parsing. In the code sample, the size value of a CSS property is changed from '10px' to '15px'.
const parse = require('postcss-values-parser').parse;
let root = parse('10px solid black');
root.nodes[0].value = '15px';
console.log(root.toString());
Other packages similar to postcss-values-parser
css-tree
css-tree is a CSS parser that produces an AST for CSS documents. It offers similar functionality for parsing CSS but is more focused on entire stylesheets rather than individual values. Compared to postcss-values-parser, css-tree provides a broader scope of CSS parsing capabilities.
css-what
css-what is a package for parsing CSS selectors. It provides functionality to parse selector strings into an understandable format but does not focus on CSS properties or values. While it offers parsing capabilities, its focus is different from that of postcss-values-parser, which is more centered on CSS values.
postcss-values-parser
A CSS property value parser built upon PostCSS,
following the same node and traversal patterns as PostCSS.
Install
Using npm:
npm install postcss-values-parser --save-dev
Please consider becoming a patron if you find this module useful.
Requirements
postcss-values-parser
Node version v6.14.0+ and PostCSS v7.0.0+.
Benefits
- Leverages PostCSS and its tokenizer under the hood
- Doesn't strip characters; eg. parenthesis
- Full AST traversal
- Ability to walk the AST for every Node type
- Convenience methods to stringify Nodes
- Follows PostCSS patterns for whitespace between Nodes
- Provides convenience properties for number units, colors, etc.
Usage
Using the parser is straightforward and minimalistic:
const { parse } = require('postcss-values-parser');
const root = parse('#fff');
const node = root.first;
Please see the Documentation for further information on using the module.
Meta
CONTRIBUTING
LICENSE (Mozilla Public License)