This video is available to students only

Generating a JavaScript AST

Exploring tools to convert (or parse) JavaScript into a real AST

Now that we have an understanding of what abstract syntax trees are, we can start generating ASTs from source code, and programmatically traverse through the different nodes in the tree.

Babel#

When previously looking at AST Explorer, the parser option was set to @babel/parser. This is a package available on npm, which means it can be installed and used to parse any source code string into an AST.

If you've worked with a frontend build pipeline, it's likely you've worked with babel in some fashion. At a high level, babel is a JavaScript compiler, commonly used to transpile modern JavaScript syntax to compatible, but older JavaScript syntax. This allows early adoption of new syntax and features before there is sufficient browser support.

It has a robust plugin system that can be used to add support for many different syntaxes, for example:

Babel performs these transpilations by converting the source code into an AST, manipulates the nodes, and converts the manipulated AST back into source code. These plugins can extend and modify the parsing and generation of the AST.

The @babel/core package wraps up most of this functionality in a single package with minimal configuration. Babel also exposes the different internal operations and functionality in a series of packages. Some of the packages, which we'll use and further explore in this lesson, include:

These lower-level packages can be used to create flexible, custom scripts to parse, generate, and manipulate ASTs.

Parsing source code#

To get started, we'll use the @babel/parser package to parse the previous code snippet into an AST.

First, create a directory, initialize a new package.json file, and add the @babel/parser dependency.

Next, create a parser.js file to execute the parser on the source code.

 

This page is a preview of Practical Abstract Syntax Trees

Start a new discussion. All notification go to the author.