recast
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
assert | 2.1.0 | 21.36 kB | MIT | prod | |
ast-types | 0.16.1 | 99.66 kB | MIT | prod | |
esprima | 4.0.1 | 50.86 kB | BSD-2-Clause | prod | |
source-map | 0.6.1 | 194.96 kB | BSD-3-Clause | prod | |
tslib | 2.6.2 | 15.59 kB | 0BSD | prod |
Recast is a powerful JavaScript library that provides functionality to transform JavaScript syntax trees, pretty-print the code in a nondestructive manner, and automatically generate source maps. Its main capability is to analyze and modify code at the syntax tree level, preserving the original formatting of any unmodified code. This makes it useful for making large-scale changes to JavaScript applications while ensuring code readability.
Using Recast in your JavaScript project starts with its installation, which can be accomplished via npm with npm install recast
. The library can be imported into your JavaScript projects using named imports. Here is an example on how you can parse and print code with Recast:
import { parse, print } from "recast";
const source = '...'; // Some JavaScript code
console.log(print(parse(source)).code);
This will output the parsed and then printed JavaScript source code. The strength of Recast becomes evident when you want to manipulates the syntax tree between parsing and printing:
import * as recast from "recast";
const code = [
"function add(a, b) {",
" return a + b;",
"}"
].join("\n");
const ast = recast.parse(code);
const add = ast.program.body[0];
const b = recast.types.builders;
ast.program.body[0] = b.variableDeclaration("var", [
b.variableDeclarator(add.id, b.functionExpression(
null,
add.params,
add.body
))
]);
const output = recast.print(ast).code;
This script takes a function declaration and turns it into a variable declaration, illustrating how you can use Recast to make changes to your JavaScript code programmatically.
Recast's documentation can be found in its source code hosted on GitHub at https://github.com/benjamn/recast. While the library doesn't have a dedicated API reference, its abilities and usage are thoroughly explained in the readme file. In addition to the basic documentation, developers looking to learn more about the types and interfaces of the library can reference the ast-types GitHub repository.