Introduction to the usage of babel in es6 (code example)
This article brings you an introduction to the usage of babel in es6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
polyfill
We all know that js always has compatibility issues, although other languages also have compatibility issues, such as c and java , but that kind of compatibility is the incompatibility of new features on old versions, while js has all kinds of weird incompatibilities. There are very complex historical and historical reasons for this, which I will not go into details here. In the past, there was only one way to solve the compatibility problem, and that was polyfill. Let’s first talk about polyfill. For example, if we want to use a new method of array includes, in a newer version of the browser, we can use it directly:
But under old browsers, such as ie10, an error will be reported:
In this case we can customize a method To solve:
function includesPolyfill(){ if(!Array.prototype.includes){ Array.prototype.includes=function(element){ for(var i=0; i<this.length><p> Define a simple method here and add it to Array.prototype. For the sake of simplicity, not much exception detection is done. Then introduce the above method into the code and execute it first, and you can do it. In js environments that are not compatible with this method, the Array.protorype.includes method is always called directly: </p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/969/215/708/1543218509651832.png" class="lazy" title="1543218509651832.png" alt="Introduction to the usage of babel in es6 (code example)"><span class="img-wrap"></span></p> <p><span class="img-wrap"></span>This is the polyfill , but polyfill has its limitations. For new features that can be implemented using old methods, polyfill can be used to solve them, such as Array.prototype.includes. However, for some new features and new syntax that cannot be implemented using old methods, such as arrows For functions, const, etc., polyfill is powerless. At this time, another method needs to be used: precompilation, or syntax conversion. </p> <p><strong>Pre-compilation</strong></p> <p>In the previous js development, there was no pre-compilation process. After finishing the js, it was deployed directly. However, with the development of front-end engineering As time went on, precompilation also appeared, especially after the emergence of languages such as typescript, coding and publishing are no longer the same way. </p> <p>Now before publishing, we always need to package, and packaging has many processes, such as resource integration, code optimization, compression and obfuscation... And in the operation of the code, we can use the new syntax Convert to the old syntax to support the new syntax. </p> <p>To put it simply, new syntax->compiler->old syntax. </p> <p>The function of the compiler is to convert the new features in the input source code into syntax. To put it bluntly, it is string processing, such as the processing of arrow functions: var add=(num1, num2)=>num1 num2 , this code cannot be executed in an environment that is not compatible with arrow functions, such as ie10</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/632/246/621/1543218556955012.png" class="lazy" title="1543218556955012.png" alt="Introduction to the usage of babel in es6 (code example)"><span class="img-wrap"></span></p> <p><span class="img-wrap"></span>But we can Through syntax conversion and compilation processing, the source code is converted into var add=function(num1, num2){return num1 num2}, so that it can be executed in browsers that do not support arrow functions</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/426/987/944/1543218573788604.png" class="lazy" title="1543218573788604.png" alt="Introduction to the usage of babel in es6 (code example)"></p> <p>Now let’s implement a simple compiler, which of course only supports arrow functions</p> <pre class="brush:php;toolbar:false">function translate(src){ let [_, name, args, body]=src.match(/\((.+)\)=>(.+)/) return `function ${name}(${args}){return ${body}}` }
For the sake of simplicity, we just use simple regular extraction for experiments and do not do any exception handling
translate('var add=(num1, num2)=>num1+num') // var add=function(num1, num2){return num1+num2}
Save the conversion result into a file, and you can use it in environments that are incompatible with arrow syntax. We can even embed this compiler in the browser, compile the source code and use the Function constructor or eval to execute it to implement the new syntax. In this case, it is called a runtime compiler, but of course it is not generally used like this. .
Using babel
Obviously, it is impossible to write such a compiler by yourself, so do you still want to do a project? At this time, we can only rely on the power of the community. Babel is such a thing. Next, we will use babel to parse arrow functions.
Initialize a project
$ mk babel-demo $ cd babel-demo $ npm init -y
Install babel:
Note: (After babel7, babel-related libraries are basically placed under the @babel namespace)
$ npm install --save-dev @babel/core @babel/cli @babel/plugin-transform-arrow-functions
@babel/core: core library
@babel/cli: command line tool
@babel/plugin-transform-arrow-functions: Arrow function syntax conversion plug-in
Writing code:
var add=(num1, num2)=>num1+num2
Use babel
to parse
$ npx babel --plugins @babel/plugin-transform-arrow-functions index.js -o bundle.js
The above command means to use babel to convert index.js and put the result into bundle.js. After execution, bundle
--plugins: add plug-in support for this conversion
-o: Output file
查看转化结果
查看新生成的bundle.js,可以发现,箭头函数被转化成了普通的funciton, 在任何环境中都支持。
var add = function (num1, num2) { return num1 + num2; };
说明
所以,对于新特性,我们可以通过使用polyfill
,也可以通过语法转化来达到兼容。
babel配置文件
很明显,使用babel cli的局限性很大,容易出错、不直观、繁琐等,所以babel还是支持配置文件的方式:
.babelrc方式
在项目新建.babelrc文件,并使用JSON语法配置
{ "presets": [...], "plugins": [...] }
直接写在package.json的babel节点
{ "name": "my-package", "version": "1.0.0", "babel": { "presets": [ ... ], "plugins": [ ... ], } }
<span style="font-family: 微软雅黑, Microsoft YaHei;">babel.config.js方式</span>
module.exports = function () { const presets = [ ... ]; const plugins = [ ... ]; return { presets, plugins }; }
两种方式大同小异,区别就是一个是动态的,一个是静态的,推荐小项目就用.babelrc,大项目就使用babel.config.js
babel配置之plugin
plugin是babel中很重要的概念,可以说,plugin才是构成babel扩展性的核心,各种各样的plugin构成了babel的生态,可以在这里看一些babel的插件列表。
.babelrc配置文件中配置插件
{ "plugins": ["@babel/plugin-transform-arrow-functions"] }
这时候我们再执行npx babel index.js -o bundle.js,就可以不指定plugin也能正常转化箭头函数了
如果一个plugin可以配置参数,则可以这么配置:
{ "plugins": [ ["@babel/plugin-transform-arrow-functions", { "spec": true }] ] }
babel配置之preset
在一个项目中,我们总是要配置一大堆的插件,这个时候,就是preset出马的时候了,那什么是preset呢?其实就是预置插件列表了,引入了一个preset就包含了一个系列的plugin
比如preset-react就包含了以下插件:
@babel/plugin-syntax-jsx
@babel/plugin-transform-react-jsx
@babel/plugin-transform-react-display-name
.babelrc配置preset-react
{ "presets": ["@babel/preset-react"] }
如果有配置项,就酱:
{ "presets": [ [ "@babel/preset-react", { "pragma": "dom", // default pragma is React.createElement "pragmaFrag": "DomFrag", // default is React.Fragment "throwIfNamespace": false // defaults to true } ] ] }
babel和webpack
添加webpack.config.js
const path=requrie('path') module.exports={ entry:path.resolve(__dirname, 'index.js'), output:{ path: path.resolve(__dirname, 'dist'), filename:'bundle.js' }, module: { rules: [ { test: /\.js$/, use: 'babel-loader' } ] }
- 添加相关依赖
$ npm install --save-dev webpack webpack-cli babel-loader " - `webpack`:`webpack`核心库 - `webpack-cli`:`webpack`命令行工具 - `babel-loader`:`babel`的`webpack loader`
打包
$ npm webpack
查看编译结果
省略无关的东西,可以看到,箭头函数也被转化成了function
/***/ "./index.js": /*!******************!*\ !*** ./index.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports) { eval("let add = function (num1, num2) {\n return num1 + num2;\n};\n\nmodule.exports = add;\n\n//# sourceURL=webpack:///./index.js?"); /***/ }) /******/ });
支持es6
支持es6可以使用@babel/present-env来代替一系列的东西,还有许多的配置像,比如兼容的浏览器版本,具体可以看这里
安装依赖包
$ npm install --save-dev @babel/preset-env
配置
{ "plugins": ["@babel/present-env"] }
打包
$ npm webpack
查看效果
/***/ "./index.js": /*!******************!*\ !*** ./index.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports) { eval("let add = function (num1, num2) {\n return num1 + num2;\n};\n\nmodule.exports = add;\n\n//# sourceURL=webpack:///./index.js?"); /***/ }) /******/ });
总结
这只是babel
功能的一个小览,了解一下babel
的基本使用和一些概念而已。
The above is the detailed content of Introduction to the usage of babel in es6 (code example). 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

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
