Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-11-26 15:55:37
forward
2364 people have browsed it

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="https://img.php.cn//upload/image/969/215/708/1543218509651832.png" 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="https://img.php.cn//upload/image/632/246/621/1543218556955012.png" 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="https://img.php.cn//upload/image/426/987/944/1543218573788604.png" 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}}`
}
Copy after login

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}
Copy after login

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
Copy after login

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
Copy after login

@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
Copy after login

Use babel to parse

$ npx babel --plugins @babel/plugin-transform-arrow-functions index.js -o bundle.js
Copy after login

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;
};
Copy after login

说明

所以,对于新特性,我们可以通过使用polyfill,也可以通过语法转化来达到兼容。

babel配置文件

很明显,使用babel cli的局限性很大,容易出错、不直观、繁琐等,所以babel还是支持配置文件的方式:

.babelrc方式

在项目新建.babelrc文件,并使用JSON语法配置

{
  "presets": [...],
  "plugins": [...]
}
Copy after login

直接写在package.json的babel节点

{
  "name": "my-package",
  "version": "1.0.0",
  "babel": {
    "presets": [ ... ],
    "plugins": [ ... ],
  }
}
Copy after login

<span style="font-family: 微软雅黑, Microsoft YaHei;">babel.config.js方式</span>

module.exports = function () {
  const presets = [ ... ];
  const plugins = [ ... ];

  return {
    presets,
    plugins
  };
}
Copy after login

两种方式大同小异,区别就是一个是动态的,一个是静态的,推荐小项目就用.babelrc,大项目就使用babel.config.js

babel配置之plugin

plugin是babel中很重要的概念,可以说,plugin才是构成babel扩展性的核心,各种各样的plugin构成了babel的生态,可以在这里看一些babel的插件列表。

.babelrc配置文件中配置插件

{
    "plugins": ["@babel/plugin-transform-arrow-functions"]
}
Copy after login

这时候我们再执行npx babel  index.js -o bundle.js,就可以不指定plugin也能正常转化箭头函数了
如果一个plugin可以配置参数,则可以这么配置:

{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ]
}
Copy after login

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"]
}
Copy after login

如果有配置项,就酱:

{
  "presets": [
    [
      "@babel/preset-react",
      {
        "pragma": "dom", // default pragma is React.createElement
        "pragmaFrag": "DomFrag", // default is React.Fragment
        "throwIfNamespace": false // defaults to true
      }
    ]
  ]
}
Copy after login

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' }
        ]
      }
Copy after login

- 添加相关依赖

$ npm install --save-dev webpack webpack-cli babel-loader
"
- `webpack`:`webpack`核心库
- `webpack-cli`:`webpack`命令行工具
- `babel-loader`:`babel`的`webpack loader`
Copy after login

打包

$ npm webpack
Copy after login
Copy after login

查看编译结果
省略无关的东西,可以看到,箭头函数也被转化成了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?");

/***/ })

/******/ });
Copy after login
Copy after login

支持es6

支持es6可以使用@babel/present-env来代替一系列的东西,还有许多的配置像,比如兼容的浏览器版本,具体可以看这里

安装依赖包

$ npm install --save-dev @babel/preset-env
Copy after login

配置

{
    "plugins": ["@babel/present-env"]
}
Copy after login

打包

$ npm webpack
Copy after login
Copy after login

查看效果

/***/ "./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?");

/***/ })

/******/ });
Copy after login
Copy after login

总结

这只是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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!