Today I learned — November 1, 2018 — 1 min read — js, css, html
Why AST Trees are Awesome
AST
stands for abstract syntax tree, and describes a universal data format to represent any kind of tree structure. In frontend development it is commonly used to describe e.g. Javascript code. Parsers like babel
uses AST trees to traverse the code, in order to read and potentially modify it in a very declaritive way, before parsing it back into JS code.
- https://github.com/babel/babylon
- https://www.npmjs.com/package/babel-traverse
- https://www.npmjs.com/package/babel-generator
But there are many other common structures that can be represented as AST trees, making it easier for us to write tools that automate reading and / or modifying to them, e.g.
- HTML (htmlparser2)
- CSS (cssom)
- GraphQL (graphql-js)
- JSON (json-to-ast)
- Markdown (remark)
- and many more
In my opinion the best tool out there to start exploring and actually working with AST trees is AST Explorer, go and check it out. Soon you'll be writing your first babel or eslint plugins, it's pretty addictive 😉
A good read on the topic: https://www.sitepoint.com/understanding-asts-building-babel-plugin/