On Parsing and Modifying JavaScript Abstract Syntax Tree

Recently I published a Yeoman generator for Express.js based APIs. I wanted to modify the JavaScript template files while implementing the Yeoman generator, for example add new routes. This requires modifying the code time to time and I wanted to do it in the right way. Which lead me to try out Esprima and Escodegen.

maxresdefault

Esprima is primarily a JavaScript/ECMAScript syntax parser which generates abstract syntax tree from a given code snippet. Escodegen on the other hand is a JavaScript/ECMAScript code generator.

Parsing JavaScript to get abstract syntax tree,

//jsfiddle.net/isurusiri/8sco0zy5/embedded/js/

One important thing to note in above code is that esprima requires the code as a string to parse it.

Modifying the abstract syntax tree,

//jsfiddle.net/isurusiri/ebk3Lcxf/1/embedded/js/

The tricky thing in here is that you need to to know the data structure that abstract syntax tree is using and you have to inject the right data structure into the right place.

Rock on!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s