#recast,_v_.[](https://travis-ci.org/benjamn/recast) [](https://gitter.im/benjamn/recast?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [](https://greenkeeper.io/)
Recastexposestwoessentialinterfaces,oneforparsingJavaScriptcode(`require("recast").parse`) and the other for reprinting modified syntax trees (`require("recast").print`).
Here'sasimplebutnon-trivialexampleofhowyoumightuse`.parse` and `.print`:
```js
import*asrecastfrom"recast";
// Let's turn this function declaration into a variable declaration.
constcode=[
"function add(a, b) {",
" return a +",
" // Weird formatting, huh?",
" b;",
"}"
].join("\n");
// Parse the code using an interface similar to require("esprima").parse.
See[ast-types](https://github.com/benjamn/ast-types) (especially the [def/core.ts](https://github.com/benjamn/ast-types/blob/master/def/core.ts)) module for a thorough overview of the `ast` API.
```js
// Grab a reference to the function declaration we just parsed.
constadd=ast.program.body[0];
// Make sure it's a FunctionDeclaration (optional).
constn=recast.types.namedTypes;
n.FunctionDeclaration.assert(add);
// If you choose to use recast.builders to construct new AST nodes, all builder
// arguments will be dynamically type-checked against the Mozilla Parser API.
constb=recast.types.builders;
// This kind of manipulation should seem familiar if you've used Esprima or the
Bydefault,Recastusesthe[EsprimaJavaScriptparser](https://www.npmjs.com/package/esprima) when you call `recast.parse(code)`. While Esprima supports almost all modern ECMAScript syntax, you may want to use a different parser to enable TypeScript or Flow syntax, or just because you want to match other compilation tools you might be using.
InordertogetanybenefitsfromRecast'sconservativepretty-printing,**itisveryimportantthatyoucontinuetocall`recast.parse`** (rather than parsing the AST yourself using a different parser), and simply instruct `recast.parse`touseadifferentparser:
```js
constacornAst=recast.parse(source,{
parser:require("acorn")
});
```
Whyisthissoimportant?Whenyoucall`recast.parse`, it makes a shadow copy of the AST before returning it to you, giving every copied AST node a reference back to the original through a special `.original` property. This information is what enables `recast.print`todetectwheretheASThasbeenmodified,sothatitcanpreserveformattingforpartsoftheASTthatwerenotmodified.
Any`parser` object that supports a `parser.parse(source)` method will work here; however, if your parser requires additional options, you can always implement your own `parse`methodthatinvokesyourparserwithcustomoptions:
```js
constacornAst=recast.parse(source,{
parser:{
parse(source){
returnrequire("acorn").parse(source,{
// additional options
});
}
}
});
```
Totakesomeoftheguessworkoutofconfiguringcommonparsers,Recastprovides[severalpreconfiguredparsers](https://github.com/benjamn/recast/tree/master/parsers), so you can parse TypeScript (for example) without worrying about the configuration details:
```js
consttsAst=recast.parse(source,{
parser:require("recast/parsers/typescript")
});
```
**Note:**SomeoftheseparsersimportnpmpackagesthatRecastdoesnotdirectlydependupon,sopleasebeawareyoumayhavetorun`npm install babylon@next` to use the `typescript`, `flow`, or `babylon` parsers, or `npm install acorn` to use the `acorn`parser.OnlyEsprimaisinstalledbydefaultwhenRecastisinstalled.
Withevery`slice`, `join`, and re-`indent`-ation,thereprintingprocessmaintainsexactknowledgeofwhichcharactersequencesareoriginal,andwhereintheoriginalsourcetheycamefrom.
Allyouhavetothinkaboutishowtomanipulatethesyntaxtree,andRecastwillgiveyoua[sourcemap](https://github.com/mozilla/source-map) in exchange for specifying the names of your source file(s) and the desired name of the map:
Andhere'sthebestpart:whenyou'redonerunningaRecastscript,ifyou'renotcompletelysatisfiedwiththeresults,blowthemawaywith`git reset --hard`,tweakthescript,andjustrunitagain.Changeyourmindasmanytimesasyoulike.Insteadoftypingyourselfintoanastycaseof[RSI](http://en.wikipedia.org/wiki/Repetitive_strain_injury), gaze upon your new wells of free time and ask yourself: what next?