What is recast?
The recast npm package is a JavaScript library for parsing, transforming, and printing JavaScript code. It allows developers to manipulate the syntax tree of JavaScript code, enabling tasks such as code refactoring, code generation, and more. Recast preserves the original formatting of the code as much as possible, which is useful when modifying existing code.
What are recast's main functionalities?
Parsing JavaScript code into an Abstract Syntax Tree (AST)
This feature allows you to parse a string of JavaScript code into an AST, which can then be manipulated or analyzed.
const recast = require('recast');
const code = 'let x = 42;';
const ast = recast.parse(code);
Transforming the AST
This feature enables you to traverse and modify the AST. In this example, all 'let' declarations are changed to 'var'.
const recast = require('recast');
const ast = recast.parse('let x = 42;');
recast.types.visit(ast, {
visitVariableDeclaration(path) {
path.node.kind = 'var';
return false;
}
});
const transformedCode = recast.print(ast).code;
Printing the modified AST back to JavaScript code
After modifying the AST, this feature allows you to print it back into a formatted JavaScript code string.
const recast = require('recast');
const ast = recast.parse('let x = 42;');
// ... modify the AST ...
const modifiedCode = recast.print(ast).code;
Other packages similar to recast
babel
Babel is a widely-used JavaScript compiler that allows you to transform your JavaScript code using various plugins. It can parse and transform modern JavaScript features into a format compatible with older browsers. Babel's plugin system is more extensive than recast, and it is often used for compiling next-gen JavaScript features down to current standards.
esprima
Esprima is a JavaScript parser that produces an AST for JavaScript code. It is similar to recast in that it can be used for static code analysis and manipulation. However, unlike recast, Esprima does not focus on preserving the original code formatting.
jscodeshift
jscodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It uses recast and babel under the hood for parsing and printing, but provides a higher-level API for transforming code, making it more accessible for writing complex codemods.