Introduction to `gonzales-pe`
`gonzales-pe` is a powerful yet lightweight CSS parser that allows developers to parse, navigate, and modify CSS stylesheets with ease. Its small footprint and efficient parsing make it an excellent choice for various applications, from quick code analysis tools to complex CSS preprocessors.
Getting Started
First, let’s get `gonzales-pe` installed:
npm install gonzales-pe
Basic Usage
After installation, you can start using `gonzales-pe` to parse CSS strings:
const gonzales = require('gonzales-pe');
const cssString = 'a { color: red; }';
const ast = gonzales.parse(cssString);
console.log(ast.toJson());
Traversing the AST
Once we have an Abstract Syntax Tree (AST), we can traverse it to gather information or make modifications:
ast.traverse(function (node) {
if (node.type === 'declaration') {
console.log(node.toString());
}
});
Modifying the AST
Modifying nodes in the AST is straightforward:
ast.traverse(function (node) {
if (node.type === 'declaration' && node.first().content === 'color') {
node.forEach('value', function (valueNode) {
valueNode.content = 'blue';
});
}
});
console.log(ast.toString());
API Overview with Examples
Parsing CSS
const ast = gonzales.parse(cssString, { syntax: 'css' });
Parsing SCSS
const ast = gonzales.parse(scssString, { syntax: 'scss' });
Finding Nodes
const nodes = ast.content.filter(node => node.type === 'class');
console.log(nodes.length);
Replacing Nodes
ast.traverse(node => {
if (node.content === 'blue') {
node.content = 'red';
}
});
Removing Nodes
ast.traverse((node, index, parent) => {
if (node.type === 'comment') {
parent.splice(index, 1);
}
});
Building an Application with `gonzales-pe`
Now that we have a good understanding of `gonzales-pe`’s capabilities, let’s build a simple application that analyzes and modifies CSS:
const gonzales = require('gonzales-pe');
const fs = require('fs');
// Read CSS file
const css = fs.readFileSync('styles.css', 'utf8');
// Parse CSS to AST
const ast = gonzales.parse(css);
// Modify AST: change all color properties to blue
ast.traverse(node => {
if (node.type === 'declaration' && node.first().content === 'color') {
node.forEach('value', valueNode => {
valueNode.content = 'blue';
});
}
});
// Output modified CSS
const modifiedCSS = ast.toString();
fs.writeFileSync('styles-modified.css', modifiedCSS);
console.log('CSS has been modified and saved to styles-modified.css');
In this example, we read a CSS file, parse it into an AST, modify the color properties, and save the modified CSS back to a file. This is just a small sample of what you can achieve with `gonzales-pe`.
Using `gonzales-pe`, you can create powerful and efficient tools to analyze, edit, and regenerate CSS stylesheets, boosting your productivity and ensuring efficient CSS management.
Hash: 058df38f04ababa3f1374e95c7030ac7900abe7b64be4a6209e690cd3e74c8eb