Detailed explanation of steps to convert babel to es6
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’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 oraddAST?
Okay, let’s first introduce a tool: astexplorer.net:This tool can convert a piece of code into AST: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 isClassDeclaration. 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 logic code and complete the conversion
module.exports = function ({ types: t }) { return { visitor: { ClassDeclaration(path) { //在这里完成转换 } } }; }
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:
Get the old AST node
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)Loop the AST object of the old node (several function nodes will be looped out)
Judge whether the type of the function is
constructor
, if so, create a normal function node by getting the data, and update the defaultconstructor
nodeto process the rest that are not
constructor
node, create a function of typeprototype
through data, and place it ines5Fns
End of the loop, put
constructor
The node is also placed ines5Fns
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 1) { path.replaceWithMultiple(es5Fns) } else { path.replaceWith(constructorFn) } } } }; }
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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools