search
HomeWeb Front-endJS TutorialUnderstanding ASTs by Building Your Own Babel Plugin

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;

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;

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;

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;
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

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

(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
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.