Home > Web Front-end > JS Tutorial > Understanding ASTs by Building Your Own Babel Plugin

Understanding ASTs by Building Your Own Babel Plugin

William Shakespeare
Release: 2025-02-18 09:24:16
Original
470 people have browsed it

Use the Babel plugin to add default unchanged data for JavaScript

This article discusses how to write a Babel plugin to add immutable data to JavaScript by default. The article explains the concept of abstract syntax tree (AST) and its role in the Babel plug-in in depth, and demonstrates how to build a way to convert normal objects and array literals into persistent data structures in Mori library through step-by-step code examples. Babel plugin.

Core points:

  • The Babel plugin converts JavaScript code by operating an abstract syntax tree (AST), allowing developers to add features such as immutable data structures to JavaScript.
  • AST is essential for understanding the structure and syntax representation of the code, which is essential for tasks such as code conversion and code style checking.
  • Creating a Babel plugin involves parsing the code into an AST, traversing and possibly modifying this AST, and then generating the modified code back to the standard JavaScript format.
  • Using online tools such as AST Explorer, developers can visualize AST, thereby helping to develop and debug Babel plugins.
  • This tutorial demonstrates the practical steps to building a Babel plugin, from setting up a development environment to writing specific transformation logic for handling arrays, objects, and assignments in JavaScript.

Language Overview:

Our goal is to design a plugin that allows us to use regular object and array literals that will be converted to persistent data structures using the Mori library.

We want to write code like this:

var foo = { a: 1 };
var baz = foo.a = 2;
foo.a === 1;
baz.a === 2;
Copy after login
Copy after login

and convert it to the following code:

var foo = mori.hashMap('a', 1);
var baz = mori.assoc(foo, 'a', 2);
mori.get(foo, 'a') === 1;
mori.get(baz, 'a') === 2;
Copy after login
Copy after login

Let's get started with MoriScript!

Babel Overview:

If we delve into Babel, we will find three important tools that handle most of the process.

Understanding ASTs by Building Your Own Babel Plugin

Analysis

Babylon is a parser that knows how to convert JavaScript code strings into computer-friendly representations called Abstract Syntax Trees (ASTs).

Convert

The

babel-traverse module allows you to explore, analyze and possibly modify AST.

Generate

Finally, the babel-generator module is used to convert the converted AST back to regular code.

What is AST?

Before continuing with this tutorial, it is crucial to understand the purpose of AST. Let's dig into what they are and why we need them.

JavaScript programs are usually composed of a series of characters, each with certain visual significance to our human brain. This works very well for us because it allows us to use matching characters ([], {}, ()), character pairs ('', "") and indents to make our program more Easy to explain.

However, this doesn't help much for the computer. For them, each character is just a numeric value in memory and they cannot use these characters to ask advanced questions like "How many variables are there in this declaration?" Instead, we need to compromise and find a way to convert our code into something that we can program and computers can understand. Please see the following code:

When we generate AST for this program, we end up with a structure as shown below:

var foo = { a: 1 };
var baz = foo.a = 2;
foo.a === 1;
baz.a === 2;
Copy after login
Copy after login

All ASTs start with the Program node at the root of the tree, which contains all the top-level statements in the program. In this case, we only have two:

Understanding ASTs by Building Your Own Babel Plugin

A VariableDeclaration with a VariableDeclarator that assigns the identifier "a" to NumericLiteral "3".

An ExpressionStatement, which in turn consists of a BinaryExpression, is described as an identifier "a", an operator " " and another NumericLiteral "5".
  1. Although they are composed of simple building blocks, the size of ASTs means they are often very complex, especially for non-trivial programs. Instead of trying to figure out AST ourselves, we can use astexplorer.net, which allows us to enter JavaScript on the left and then output an exploreable AST representation on the right. As we continue, we will use this tool specifically to understand and experiment with the code.
To be consistent with Babel, make sure to select "babylon6" as the parser.

When writing Babel plugin, our job is to get the AST and then insert/mov/replace/delete some nodes to create a new AST that can be used to generate the code.

Settings:

Before starting, make sure node and npm are installed. Then create a folder for the project, create a file and install the following development dependencies.

We will then create a file for our plugin and export a default function in it. package.json

var foo = mori.hashMap('a', 1);
var baz = mori.assoc(foo, 'a', 2);
mori.get(foo, 'a') === 1;
mori.get(baz, 'a') === 2;
Copy after login
Copy after login
This function exposes the interface of visitor mode, and we will return to it later.

Finally, we will create a runner to test our plugin as we go.
var a = 3;
a + 5
Copy after login

We can call this script using the name of the MoriScript sample file to check if it generates the JavaScript we expect. For example,

.

mkdir moriscript && cd moriscript
npm init -y
npm install --save-dev babel-core
Copy after login

(The following continues to introduce the processing of arrays, objects and assignments, as well as the final conclusions and FAQs, which are consistent with the original text, but the language and structure have been adjusted to make it smoother and more natural. Due to space limitations , pseudo-original content for the remaining part of the original text is omitted here. )node run.js example.ms

The above is the detailed content of Understanding ASTs by Building Your Own Babel Plugin. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template