What is pug-walk?
The pug-walk npm package is designed for walking through the abstract syntax tree (AST) of Pug templates. It allows developers to traverse and manipulate nodes in the AST, enabling operations such as modification, filtering, and analysis of Pug templates.
What are pug-walk's main functionalities?
Walking the AST
This example demonstrates how to traverse a Pug template's AST to find all `div` tags and add an `id` attribute to them. The `walk` function takes the AST and a callback function that is applied to every node. If the node matches the criteria (a `div` tag in this case), a new attribute is added.
const pug = require('pug');
const pugWalk = require('pug-walk');
const ast = pug.parser.parse('div(class=classes)');
pugWalk.walk(ast, (node, replace) => {
if (node.type === 'Tag' && node.name === 'div') {
node.attrs.push({
name: 'id',
val: '"dynamic-id"',
mustEscape: false
});
replace(node);
}
});
Filtering Nodes
This code snippet shows how to filter nodes of a specific type, in this case, `Conditional` nodes, from a Pug template's AST. The `walk` function is used to traverse the AST, and nodes that match the specified condition are added to an array for further processing.
const pug = require('pug');
const pugWalk = require('pug-walk');
const ast = pug.parser.parse('div
if condition
p True
else
p False');
const filteredNodes = [];
pugWalk.walk(ast, node => {
if (node.type === 'Conditional') {
filteredNodes.push(node);
}
}, {includeDependencies: true});
Other packages similar to pug-walk
htmlparser2
htmlparser2 is a fast HTML parser with a similar API to pug-walk but for HTML instead of Pug templates. It provides a robust and forgiving parser and a flexible tree traversal API, but it does not directly support Pug's syntax or AST structure.
cheerio
cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It allows for manipulation and traversal of HTML documents with a familiar jQuery-like syntax. While it offers similar DOM manipulation and traversal capabilities, it operates on HTML rather than Pug's AST.
esprima
esprima is a high performance, standard-compliant ECMAScript parser that provides a similar AST traversal and manipulation API for JavaScript code. While it serves a similar purpose in traversing and manipulating ASTs, it is focused on JavaScript rather than Pug templates.
pug-walk
Walk and transform a pug AST
Installation
npm install pug-walk
Usage
var lex = require('pug-lexer');
var parse = require('pug-parser');
var walk = require('pug-walk');
var ast = walk(parse(lex('.my-class foo')), function before(node, replace) {
if (node.type === 'Text') {
replace({ type: 'Text', val: 'bar', line: node.line });
}
}, function after(node, replace) {
}, {includeDependencies: true});
assert.deepEqual(parse(lex('.my-class bar')), ast);
License
MIT