The Webpack build Tool---Babel configuration file. BABELRC (iii)

Source: Internet
Author: User
Tags babeljs

Read Catalogue

One: Understand the Babel configuration file. BABELRC Basic Configuration Items

Two: Configure Babel in Webpack

Back to Top

One: Understand the Babel configuration file. BABELRC Basic Configuration Items

1. What is Babel? What is it used for?

ES6 is the next generation of JavaScript language standards released in 2015, which introduces new syntax and APIs that make it easier to write JS code, such as Class,let,for...of promise and so on, But unfortunately these new JS features are only supported by the latest version of the browser, but the lower version of the browser is not supported, then the lower version of the browser needs a conversion tool, the ES6 code into the browser can recognize the code, Babel is such a tool. It can be understood that Babel is a compiler for JavaScript syntax.

2. Babel compiler
During Babel execution, the configuration is read from the. babelrc file in the root directory of the project: BABELRC is a JSON-formatted file.
In the. BABELRC configuration file, it is primarily configured with presets (presets) and plug-ins (plugins): The BABELRC configuration file is generally as follows.

{  "plugins": [     [      "Transform-runtime",      {        false       }     ]   ],   "presets": [     [       "env",       {         false]         }     ],     "Stage-2",     "react"  ]}

2.1 Plugins
This property tells Babel to use those plug-ins that can control how the code is converted.

1. Understanding Babel-polyfill and Babel-runtime and Babel-plugin-transform-runtime

Babel default to only the new JavaScript syntax, not the new API, such as Iterator, Generator, Set, Maps, proxies, reflect,symbol,promise and other global objects. And some methods on global objects, such as Object.assign, are not transcoded.
For example, ES6 adds a Array.form method to the Array object, Babel does not transcode the method, and if you want to run this method, you must use Babel-polyfill to convert.

Therefore: Babel-polyfill and babel-runtime are to solve the problem of the new API and this global object or global object method is insufficient, so you can use these two plug-ins can be converted.

So what's the difference between them?
The principle of Babel-polyfill is that when there are some methods that are not implemented in the running environment, Babel-polyfill will do the compatibility.
babel-runtime It compiles es6 into ES5 to execute. We use ES6 's syntax to write and eventually compile to es5 through Babel-runtime. That is, the browser does not support ES6, as long as the ES6 syntax, it will be transcoded to ES5. So there's a lot of redundant code.

Babel-polyfill It is implemented by adding methods to global objects and prototype of built-in objects. For example, the operating environment does not support the Array.prototype.find method, the introduction of Polyfill, we can use the Es6 method to write, but the disadvantage is that it will cause global space pollution.

babel-runtime: It doesn't pollute the prototype of global objects and built-in objects, for example we need Promise, we just need to import Promise from ' Babel-runtime/core-js/promise ' , which not only avoids polluting the global object, but also reduces unnecessary code.

Although babel-runtime can solve the babel-polyfill in the prevention of pollution in the global object, but it has its own shortcomings, such as, if I now have 100 files or even more words, we need a file plus import Promise from ' Babel-runtime/core-js/promise '? That's certainly not possible, so this time out a called babel-plugin-transform-runtime,
It can help us avoid the pain of importing imports manually, and it also makes a common method of pulling away. For example, we have 100 modules that use promise, but promise's polyfill only has 1 copies.
This is the role of the Babel-plugin-transform-runtime plugin.

2. Understanding the configuration of Babel-plugin-transform-runtime some options

So through the above understanding, we can configure the Transform-runtime by the following plugins; The following code:

{  ' plugins ': [    [      ' Transform-runtime ',       {        false,         false ,         true ,        ' ModuleName ': ' Babel-runtime '      }    ]  ]}

Configuration items can be crossing net, view official website

Helpers: The default value is True, indicating whether to turn on inline Babel helpers (that is, Babel or some object method functions that exist in the environment), such as: extends,etc
The name is replaced when the module name is called.

Polyfill: The default value is True, indicating whether to convert the built-in objects (Promise, Set, Map) to non-global pollution.

regenerator: The default value is True, if the generator function is turned on to use the Regenerator runtime to avoid polluting the global domain.

modulename: The default value is babel-runtime when the Secondary Setup module (module) name/path is called.
such as the following settings:

{  "modulename": "Flavortown/runtime"}

The import introduction file looks like this:

Import extends from ' flavortown/runtime/helpers/extends ';

3 presets
The Presets property tells Babel which new syntax attributes are used by the source code to be converted, and presets is a set of plugins.

3.1 Understanding Babel-preset-env

Like what:

BABEL-PRESET-ES2015: The ES6 code can be compiled into ES5.
BABEL-PRESET-ES2016: You can compile the code for ES7 to ES6.
BABEL-PRESET-ES2017: You can compile the code for ES8 to ES7.
Babel-preset-latest: Supports new features for all existing ECMAScript versions.

For example, if we need to convert ES6 syntax, we can introduce plugins as needed in the. BABELRC plugins, such as:
Check-es2015-constants, Es2015-arrow-functions, es2015-block-scoped-functions and so on dozens of different roles of plugin:
Then the configuration item may be as follows:

// . BABELRC {  "plugins": [    "Check-es2015-constants",    "Es2015-arrow-functions",     "Es2015-block-scoped-functions",    //  ...   ]}

But for the convenience of the Babel team, dozens of transform plugins of the same genus ES2015 are assembled into babel-preset-es2015 a preset, All we need to do is to add es2015 a configuration to the. BABELRC presets support for all ES2015 syntax:
The following configuration:

// . BABELRC {  "presets": [    "es2015"  ]}

But as time goes by, there may be multiple versions of plugins in the future, such as bebel-preset-es2018,.... Wait a minute.
So babel-preset-env appears, its function is similar to babel-preset-latest, it will be based on the target environment to choose the new features not supported to translate.

You first need to install in the project, such as the following command:

NPM Install babel-preset-env--save-dev

In the. BABELRC configuration file, you can configure the following simple:

{  "presets": [' env ']}

We can also simply configure the configuration of the browsers supported by the project

1. Support for the last two versions of each browser and the Polyfill code conversion required for safari greater than or equal to 7, we can configure as follows:

{  ' presets ': [    ' env ', {      ' target ':{        ' browsers ': [' last 2 Versions ', ' Safari >= 7 '}}    ]  ]}

2. Browsers that support more than 5% of the market share can be configured as follows:

{  ' presets ': [    ' env ',      {' target ':{        ' browsers ': ' > 5% '       }    }]  ]}

3. Specify the browser version, which can be configured as follows:

{  ' presets ': [    [' env ', {      ' target ':{        ' chrome ': 56       }    }]  ]}

node. js
If you compile the node. js code through Babel, you can set "Target.node" to be ' current ', meaning that it supports the currently running version of Nodejs.
The following configuration code:

{  "presets": [    ["env", {      "targets": {        "node": "Current"       }    }]  ]}

Understand the configuration of the options in Babel-preset-env:
1. Targets: {[string]: number | string}, default = {};
The meaning is to support a running environment of the object, such as support node version, can be configured as follows: node: ' 6.0 ';
Operating environment: Chrome, Opera, Edge, Firefox, Safari, ie, iOS, Android, node, electron

2. Targets.browsers <array | String>
Browser-enabled configuration items that can be queried using the Browserslist (https://github.com/browserslist/browserslist)
For example, the above supports the last two versions of each browser and Safari is greater than or equal to 7 versions. Configured as above.

3. Modules
The meaning of this parameter is: Enable converting the ES6 module syntax to another module type. Setting this to false will not convert the module. The default is ' Commonjs '.
The value can be as follows:
' AMD ' | ' UMD ' | ' Systemjs ' | ' Commonjs ' | False

In the project we will generally see the following configuration, set Modules:false, the following code configuration:

"Presets": [   ' env ',   {     false   }]

The goal is to use Babel to convert ES6 's module syntax to a modular standard syntax like AMD, COMMONJS,UMD, but now Webpack has done it for me, so we don't need Babel to do it, Therefore, you need to set modules to False in the Babel configuration item because it defaults to COMMONJS, otherwise it will cause a conflict.

4. Loose, this parameter value defaults to False.
The implication is: allow them to enable "loose" conversions for any plug-in for this preset.

5. Include: contains some plug-ins, the default is [];
For example, include the arrow function, can be configured as follows:

{  "presets": [    ["env", {      "targets": {        "browsers": ["Last 2 Versions "," Safari >= 7 "]      },      " include ": [" Transform-es2015-arrow-functions "," Es6.map "]    }]  ]}

6. Exclude; exclude which plugins, the default is [];
For example, to exclude generators, you can configure the following:

{  "presets": [    ["env", {      "targets": {        "browsers": ["Last 2 Versions", "Safari >= 7"]      },      " Exclude ": [" Transform-regenerator "," Es6.set "]    }]  }

3.2 Understanding Babel-presets-stage-x
Official presets (preset), there are two kinds, one is by year (babel-preset-es2017), one is by stage (babel-preset-stage-0). This is mainly based on the TC39 committee ecmascrpit release process. So far there are 4 different stage presets:

Babel-preset-stage-0Babel-preset-stage-1Babel-preset-stage-2Babel-preset-stage-3

Each of these presets relies on the following late-stage presets, the smaller the number, the more closely the stage, the more dependent. That is to say, stage-0 includes stage-1, and so on. So stage-0 contains the contents of STAGE-1/2/3. So if we don't know which stage-x we need, it's good to introduce stage-0 directly.

STAGE0 (https://babeljs.io/docs/en/babel-preset-stage-0) is just a nice radical idea, some Babel plug-ins implement support for these features, but are unsure whether they will be set as standard.

Stage1 (https://babeljs.io/docs/en/babel-preset-stage-1) merit the inclusion of standard features.

Stage2 (HTTPS://BABELJS.IO/DOCS/EN/BABEL-PRESET-STAGE-2) The specification has been drafted and will be included in the standard.

Stage3 (https://babeljs.io/docs/en/babel-preset-stage-3) This feature specification has been finalized, and the big browser vendors and the node. JS community have begun to implement.

But we only need to install the stage you want when we use it: for example babel-preset-stage-2, the installation command is as follows:

NPM Install--save-dev babel-preset-stage-2
Back to Top

Two: Configure Babel in Webpack

Now that we've learned about Babel, we need to know how to use it in Webpack. Since Babel is doing the conversion code, all the need to use loader to convert, so we need to configure Babel-loader.

Before installing Babel-loader, we need to install Babel-core, because Babel-core is the core of the Babel compiler, so it means that if we need babel-loader for ES6 transcoding, we first need to install Babel-core, install the command as follows:

NPM Install--save-dev Babel-core

Then we install Babel-loader, the command is as follows:

NPM Install--save-dev Babel-loader

Then we need to install babel-preset-env, Babel-plugin-transform-runtime, babel-preset-stage-2, as below command installation

NPM Install--save-dev  babel-preset-env babel-plugin-transform-runtime babel-preset-stage-2

So the. BABELRC can be configured as follows:

{  "plugins": [     [      "Transform-runtime",      {        false       }     ]   ],   "presets": [     [       "env",       {         false]         }     ],     "stage-2"  ]}

Before we do the demo, let's start by looking at the directory structure as follows:

# # # directory structure as follows: Demo1 # project Name| |---Dist # directory files generated after packaging| |---Node_modules # all dependent packages| |---JS # Store all JS files| | |--Demo1.js| | |--main.js # JS Portal file|   || |---webpack.config.js # webpack config file| |---index.html # HTML file| |---Styles # Store all CSS style files| |---. Gitignore| |---readme.md| |---Package.json| |---. BABELRC # Babel transcoding file

Therefore, the Babel-loader configuration needs to be added in the Webpack configuration, as follows:

Module.exports = {  module: {    rules: [      {        /\.js$/,        //  exclude Files         Loader: ' Babel-loader '}}  }

Webpack all configurations are as follows code

Const PATH = require (' path ');//plugin for extracting CSSConst Extracttextplugin = require (' Extract-text-webpack-plugin '); Const Clearwebpackplugin= Require (' Clean-webpack-plugin '); Module.exports={entry:'./js/main.js ', Output: {filename:' Bundle.js ',    //Place the output files in the Dist directoryPath:path.resolve (__dirname, ' dist ')), Publicpath:'/dist '}, Mode:' Development ', module: {rules: [{//use regular to match CSS files to be converted with this loaderTest:/\.css$/, Loaders:ExtractTextPlugin.extract ({//Convert. css files to use the loaderUse: [' Css-loader ']})}, {test:/\. (png|jpg) $/, Loader:' Url-loader ', Options: {limit:10000, Name:' [name]. [ext] '}}, {test:/\.js$/, exclude:/(Node_modules)/,//Exclude FilesLoader: ' Babel-loader '}]}, resolve: {//modules: [' plugin ', ' JS ']}, Externals: {jquery:' JQuery '}, Devtool:' Source-map ', plugins: [//new Clearwebpackplugin ([' Dist ']),    NewExtracttextplugin ({//the name of the. css file extracted from the JS filefilename: ' Main.css '}) ]};

The Package.json installation dependency package is as follows:

{  "Name": "Demo1",  "Version": "1.0.0",  "description": "",  "Main": "Index.js",  "Scripts": {    "Dev": "Webpack-dev-server--progress--colors--devtool source-map--hot--inline",    "Build": "Webpack--progress--colors"  },  "Devdependencies": {    "Babel-core": "^6.26.3",    "Babel-loader": "^7.1.5",    "Babel-plugin-transform-runtime": "^6.23.0",    "Babel-preset-env": "^1.7.0",    "Babel-preset-stage-2": "^6.24.1",    "Clean-webpack-plugin": "^0.1.19",    "Css-loader": "^1.0.0",    "Extract-text-webpack-plugin": "^4.0.0-beta.0",    "File-loader": "^1.1.11",    "Path": "^0.12.7",    "Style-loader": "^0.21.0",    "Uglifyjs-webpack-plugin": "^1.2.7",    "Url-loader": "^1.0.1",    "Webpack": "^4.16.1",    "Webpack-cli": "^3.0.8",    "Webpack-dev-server": "^3.1.4"  },  "Dependencies": {    "Axios": "^0.18.0",    "jquery": "^3.3.1"  }}

Now we continue to write the Generator function within the Main.js code as follows:

function* g () {  ' a ';  ' B ';  ' C ';   return ' Ending ';} var gen =//  returns object {value: ' A ', done:false} for(Let A of [ , 4]) {  //  print out 1, 2, 3, 4}

Then rerun the package command after NPM run Dev, opening the browser to run can see the console output {value: "A", done:false}, stating that Babel has been translated.

The Webpack build Tool---Babel configuration file. BABELRC (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.