search
HomeWeb Front-endJS TutorialIntroduction to the usage of babel in es6 (code example)

Introduction to the usage of babel in es6 (code example)

Nov 26, 2018 pm 03:55 PM
babeles6javascript

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:

Introduction to the usage of babel in es6 (code example)

But under old browsers, such as ie10, an error will be reported:

Introduction to the usage of babel in es6 (code example)

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/imghwm/default1.png" data-src="https://img.php.cn//upload/image/969/215/708/1543218509651832.png?x-oss-process=image/resize,p_40" 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/imghwm/default1.png" data-src="https://img.php.cn//upload/image/632/246/621/1543218556955012.png?x-oss-process=image/resize,p_40" 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/imghwm/default1.png" data-src="https://img.php.cn//upload/image/426/987/944/1543218573788604.png?x-oss-process=image/resize,p_40" 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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

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.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)