国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Use the Babel plugin to add default unchanged data for JavaScript
Analysis
Convert
Generate
Home Web Front-end JS Tutorial Understanding ASTs by Building Your Own Babel Plugin

Understanding ASTs by Building Your Own Babel Plugin

Feb 18, 2025 am 09:24 AM

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

See all articles