Babel conversion es6 method implementation
This time I will bring you the implementation of the babel conversion to es6 method. What are the precautions for babel conversion to es6? The following is a practical case, let's take a look.
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’sclass to es5”.
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:- npm install webpack webpack-cli babel-core -D
- Create a new webpack.config.js
- Configure webpack.config.js
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 add a new AST? Okay, let’s first introduce a tool: astexplorer.net:This tool can convert a piece of code into AST:ClassDeclaration. Okay, let’s search in the documentation and find that just calling the following api is enough:
- Export a function in index.js
- The function returns an object, the object has a visitor parameter (must be called visitor)
- Query through astexplorer.net
Outputclass
corresponding The AST node is
ClassDeclaration - Set a capture function
ClassDeclaration
in the vistor, which means I want to capture all
in the js code ClassDeclarationNode
- Write logical code and complete the conversion
module.exports = function ({ types: t }) { return { visitor: { ClassDeclaration(path) { //在这里完成转换 } } }; }
{ types:t} The thing is to deconstruct the
variablet from the parameters. It is actually t in the babel-types document (red box in the picture below), which is used to create nodes:
第二个参数 path
,它是捕获到的节点对应的信息,我们可以通过 path.node
获得这个节点的AST,在这个基础上进行修改就能完成了我们的目标。
如何把es6的class转换为es5的类
上面都是预备工作,真正的逻辑从现在才开始,我们先考虑两个问题:
我们要做如下转换,首先把es6的类,转换为es5的类写法(也就是普通函数),我们观察到,很多代码是可以复用的,包括函数名字、函数内部的代码块等。
如果不定义class中的 constructor
方法,JavaScript引擎会自动为它添加一个空的 constructor()
方法,这需要我们做兼容处理。
接下来我们开始写代码,思路是:
拿到老的AST节点
创建一个数组用来盛放新的AST节点(虽然原class只是一个节点,但是替换后它会被若干个函数节点取代) 初始化默认的
constructor
节点(上文提到,class中有可能没有定义constructor)循环老节点的AST对象(会循环出若干个函数节点)
判断函数的类型是不是
constructor
,如果是,通过取到数据创建一个普通函数节点,并更新默认constructor
节点处理其余不是
constructor
的节点,通过数据创建prototype
类型的函数,并放到es5Fns
中循环结束,把
constructor
节点也放到es5Fns
中判断es5Fns的长度是否大于1,如果大于1使用
replaceWithMultiple
这个API更新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 == 'constructor') { 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('prototype'), 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) } } } }; }
优化继承
其实,类还涉及到继承,思路也不复杂,就是判断AST中没有 superClass
属性,如果有的话,我们需要多添加一行代码 Bird.prototype = <a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a>.create(Parent)
,当然别忘了处理 super
关键字。
打包后代码
运行 npm start
打包后,我们看到打包后的文件里 class
语法已经成功转换为一个个的es5函数。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Babel conversion es6 method implementation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

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 implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

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

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.
