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.
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:
Add an attribute to a JSX element:
Note: the
visited
param name in the above condition is to avoid another traversal in the same node and causing an infinite loop as babel doesn't guarantee visiting the same node only one time. there might be a better way of doing it but till i figure it out, that is the reason for the condition.
Wrapping an Element in a new one:
Get all key/value props of 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:
- Search babel plugins on GitHub and see how it is being used in different contexts.
- Search Codota for the method I’m trying to use e.g. https://www.codota.com/code/javascript/functions/%2540babel%252Ftypes/stringLiteral (tbh, I found their search much better than Github's).
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!
Originally published at https://felfel.dev.