Abstract Syntax Trees by example

Babel is a very powerful code generator and parser, but the documentation doesn’t have many examples of how to use it for parsing, generating, and manipulating abstract syntax trees, I’m collecting some here from my own usage of it.

Mahmoud Felfel
Jan 6 · 2 min read

I’m currently working on a side project which needs a lot of JSX/HTML parsing, manipulation, and generation using Abstract Syntax Trees (AST).

ASTs are very powerful and you can use them to build your own babel plugins, macros, or use them directly as part of your app to do custom parsing and manipulations of your code.

You can read more about the basics of ASTs here:

One major resource you will need to check a lot while working on ASTs is the babel types document, but a big issue I found with it is the lack of examples on how to use the different methods and what type of code will be expected as an output.

So as a resource for myself and others, I’m collecting here some examples from my own usage, and will be updating this post over time with new ones as I’m working on the project:

For all the examples, assume I’m importing these libs:

babel imports

Add an attribute to a JSX element:

Add an attribute to a JSX element

Wrapping an Element in a new one:

Wrapping an Element in a new one

Get all key/value props of an Element

Get all key/value props of an Element

Apply New Props to an Element

Apply New Props to an Element

To render the generated JSX output, I use this lib react-jsx-parser, I checked its source code and it seems to be using Acorn which is another AST parser/generator (babel is actually based on Acorn).

Some other good resources I found for examples of how to use a specific method:

Also, I found AST Explorer to be useful in quickly trying specific methods and see their output, but what I missed there was the autocomplete of each method signature that VS code gives. (Kent C. Dodds in this video shows how to use it to build babel macros).

Thanks for reading!

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store