Home Web Front-end JS Tutorial Detailed explanation of steps to convert babel to es6

Detailed explanation of steps to convert babel to es6

Apr 20, 2018 am 11:23 AM
babel Detailed explanation Convert

This time I will bring you a detailed step-by-step guide to converting babel to es6. What are the precautions for converting babel to es6? The following is a practical case, let’s take a look.

Babel is a transcoder, which is currently used when developing react and vue projects. It can convert es6 syntax to es5, as well as JSX and other syntax.

In our projects, we all convert specific codes, such as env, stage-0, etc., by configuring plug-ins and presets (a collection of multiple plug-ins).

In fact, Babel can convert any code through custom plug-ins. Next, let’s learn about Babel through an example of “converting es6’s

class to es5”.

The content is as follows:

webpack environment configuration

Everyone should have configured the babel-core loader and its role It provides the core API of Babel. In fact, our code conversion is implemented through plug-ins.

Next, we will implement an es6 class conversion plug-in ourselves without using third-party plug-ins. First perform the following steps to initialize a project:

  1. npm install webpack webpack-cli babel-core -D

  2. Create a new webpack.config.js

  3. Configure webpack.config.js

If our plug-in name wants to be called transform-class, we need to make the following configuration in the webpack configuration:

Next we create a new folder of babel-plugin-transform-class in node_modules to write the logic of the plug-in (if it is a real project, you need to write this plug-in and Publish to npm warehouse), as shown below:

The red area is my newly created folder, and above it is a standard plug-in project structure. For convenience, I just write The core index.js file.

How to write a babel plug-in

The babel plug-in is actually implemented through AST (Abstract Syntax Tree).

babel helps us convert js code into AST, then allows us to modify it, and finally convert it into js code.

So there are two questions involved: What is the mapping relationship between js code and AST? How to replace or

addAST?

Okay, let’s first introduce a tool: astexplorer.net:

This tool can convert a piece of code into AST:

As shown in the figure , we wrote an es6 class, and then the right side of the webpage generated an AST for us, which actually turned each line of code into an

object, so that we implemented a mapping.

Introducing another document: babel-types:

This is the API document for creating AST nodes.

For example, if we want to create a class, we first convert it in astexplorer.net and find that the AST type corresponding to the class is

ClassDeclaration. Okay, let’s search in the documentation and find that just calling the following api is enough:

The same goes for creating other statements. With the above two things, we can No conversions were made.

Now we start to actually write a plug-in, which is divided into the following steps:

  1. Export a function in index.js

  2. The function returns an object, the object has a visitor parameter (must be called visitor)

  3. Query through astexplorer.net

    Outputclass corresponding The AST node is ClassDeclaration

  4. Set a capture function

    ClassDeclaration in the vistor, which means I want to capture all in the js code ClassDeclaration Node

  5. Write logic code and complete the conversion

module.exports = function ({ types: t }) {
 return {
  visitor: {
   ClassDeclaration(path) {
    //在这里完成转换
   }
  }
 };
}
Copy after login

There are two parameters in the code. The first {types:t} thing is to deconstruct the variablet from the parameters, which is actually t in the babel-types document (red box in the picture below), which is used to create nodes:

The second parameter path, it It is the information corresponding to the captured node. We can obtain the AST of this node through path.node, and modify it on this basis to achieve our goal.

How to convert es6 class to es5 class

The above are all preliminary work, the real logic starts from now, let’s first Consider two questions:

We need to do the following conversion. First, convert es6 classes into es5 class writing (that is, ordinary functions). We have observed that many codes can be reused, including functions. Names, code blocks inside functions, etc.

If the constructor method in class is not defined, the JavaScript engine will automatically add an empty constructor for it () method, which requires us to do compatibility processing.

Next we start writing code, the idea is:

  1. Get the old AST node

  2. Create an array with To hold the new AST node (although the original class is only one node, it will be replaced by several function nodes after replacement) Initialize the default constructor node (mentioned above, the class may not be defined constructor)

  3. Loop the AST object of the old node (several function nodes will be looped out)

  4. Judge whether the type of the function is constructor, if so, create a normal function node by getting the data, and update the default constructor node

  5. to process the rest that are not constructor node, create a function of type prototype through data, and place it in es5Fns

  6. End of the loop, put constructor The node is also placed in es5Fns

  7. Determine whether the length of es5Fns is greater than 1. If it is greater than 1, use replaceWithMultiple This API updates the AST

module.exports = function ({ types: t }) {
 return {
  visitor: {
   ClassDeclaration(path) {
    //拿到老的AST节点
    let node = path.node
    let className = node.id.name
    let classInner = node.body.body
    //创建一个数组用来成盛放新生成AST
    let es5Fns = []
    //初始化默认的constructor节点
    let newConstructorId = t.identifier(className)
    let constructorFn = t.functionDeclaration(newConstructorId, [t.identifier('')], t.blockStatement([]), false, false)
    //循环老节点的AST对象
    for (let i = 0; i < classInner.length; i++) {
     let item = classInner[i]
     //判断函数的类型是不是constructor
     if (item.kind == &#39;constructor&#39;) {
      let constructorParams = item.params.length ? item.params[0].name : []
      let newConstructorParams = t.identifier(constructorParams)
      let constructorBody = classInner[i].body
      constructorFn = t.functionDeclaration(newConstructorId, [newConstructorParams], constructorBody, false, false)
     } 
     //处理其余不是constructor的节点
     else {
      let protoTypeObj = t.memberExpression(t.identifier(className), t.identifier(&#39;prototype&#39;), false)
      let left = t.memberExpression(protoTypeObj, t.identifier(item.key.name), false)
      //定义等号右边
      let prototypeParams = classInner[i].params.length ? classInner[i].params[i].name : []
      let newPrototypeParams = t.identifier(prototypeParams)
      let prototypeBody = classInner[i].body
      let right = t.functionExpression(null, [newPrototypeParams], prototypeBody, false, false)
      let protoTypeExpression = t.assignmentExpression("=", left, right)
      es5Fns.push(protoTypeExpression)
     }
    }
    //循环结束,把constructor节点也放到es5Fns中
    es5Fns.push(constructorFn)
    //判断es5Fns的长度是否大于1
    if (es5Fns.length > 1) {
     path.replaceWithMultiple(es5Fns)
    } else {
     path.replaceWith(constructorFn)
    }
   }
  }
 };
}
Copy after login

Optimizing inheritance

In fact, classes also involve inheritance, and the idea is not complicated. It just determines whether there is any in the AST superClass attribute, if any, we need to add one more line of code Bird.prototype = Object.create(Parent), of course don’t forget to handle the super key Character.

Packaged code

Runnpm start After packaging, we see the packaged file class

The syntax has been successfully converted into es5 functions one by one.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to upgrade vue cli to webapck4

Detailed steps for AngularJS application modularization

vue-cli 3.0 What beginners need to know

The above is the detailed content of Detailed explanation of steps to convert babel to es6. 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

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

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)

Practical tips for converting full-width English letters into half-width form Practical tips for converting full-width English letters into half-width form Mar 26, 2024 am 09:54 AM

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the implementation method of converting PHP months to English months Detailed explanation of the implementation method of converting PHP months to English months Mar 21, 2024 pm 06:45 PM

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone Mar 21, 2024 pm 01:21 PM

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

How to convert full-width English letters into half-width letters How to convert full-width English letters into half-width letters Mar 25, 2024 pm 02:45 PM

How to convert full-width English letters into half-width letters In daily life and work, sometimes we encounter situations where we need to convert full-width English letters into half-width letters, such as when entering computer passwords, editing documents, or designing layouts. Full-width English letters and numbers refer to characters with the same width as Chinese characters, while half-width English letters refer to characters with a narrower width. In actual operation, we need to master some simple methods to convert full-width English letters into half-width letters so that we can process text and numbers more conveniently. 1. Full-width English letters and half-width English letters

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

PHP Tutorial: How to convert int type to string PHP Tutorial: How to convert int type to string Mar 27, 2024 pm 06:03 PM

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

See all articles