How to use the prettyPrint function from recast
Find comprehensive JavaScript recast.prettyPrint code examples handpicked from public code repositorys.
recast.prettyPrint is a function in the Recast library that takes an AST (Abstract Syntax Tree) and returns a formatted string representation of the code.
GitHub: wangrui233/my-js
239 240 241 242 243 244 245 246 247 248
null, Anonymize the function expression add.params, add.body )) ]) const output = recast.prettyPrint(ast, { tabWidth: 2 }).code log(output) log(output(1, 3)) recast.run(function (ast, printSource) { printSource(ast)
+ 33 other calls in file
How does recast.prettyPrint work?
recast.prettyPrint
is a function in the Recast library that takes an AST (Abstract Syntax Tree) and returns a formatted string representation of the code.
When recast.prettyPrint
is called with an AST as input, it recursively walks the tree and generates a string representation of the code that includes proper indentation and line breaks.
The formatting of the output can be customized by passing options to the recast.print
function. For example, you can specify the number of spaces to use for indentation or disable semicolons at the end of statements.
Here is an example of using recast.prettyPrint
to format an AST:
javascriptconst recast = require("recast");
const { parse } = require("acorn");
const code = "function square(n) { return n * n; }";
const ast = parse(code);
const formattedCode = recast.prettyPrint(ast, { tabWidth: 2 }).code;
console.log(formattedCode);
In this example, we start with a string of code and use acorn
to parse it into an AST. We then pass the AST to recast.prettyPrint
, along with an options object specifying a tab width of 2. The resulting string is logged to the console.
The output of recast.prettyPrint
will be a formatted string representation of the code, like this:
javascriptfunction square(n) {
return n * n;
}
By default, recast.prettyPrint
will include semicolons at the end of statements and use two spaces for indentation. However, you can customize these options by passing different values to the recast.print
function.
Ai Example
1 2 3 4 5 6 7 8
const recast = require("recast"); const { parse } = require("acorn"); const code = "function square(n) { return n * n; }"; const ast = parse(code); const formattedCode = recast.prettyPrint(ast).code; console.log(formattedCode);
In this example, we use acorn to parse a string of code into an AST, and then pass the AST to recast.prettyPrint to format it. We don't pass any options to recast.prettyPrint, so the default formatting is used. The output of recast.prettyPrint will be a formatted string representation of the code, like this: javascript Copy code
recast.parse is the most popular function in recast (1784 examples)