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).
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:
visitedparam 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
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.
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.