What it does: Convert the ES6+ version of code to ES5 code so that it can run in both the current environment and the older browser environment.

This means that you can write code in ES6 without worrying about whether your current environment supports it.

Configure.babelrc

The first step in using Babel is to configure the.babelrc file. This file is stored in the root directory of the project and is used to set transcoding rules and plug-ins. The basic format is as follows:

{
	"presets": [...]. ."plugins": [...]. }Copy the code

The presets field sets transcoding rules and can be installed as required.

# ES2015 Transcoding rules$NPM install -- save-dev babel-preset- ES2015# react transcoding rules$NPM install -- save-dev babel-preset-react# ES7 Transcoding rules for syntax proposals in different stages (there are four stages), select one$NPM install - save-dev Babel -preset-stage-0 $NPM install - save-dev Babel -preset-stage-1 $NPM install - save-dev Babel-preset -stage-2 $NPM install -- save-dev babel-preset-stage-3Copy the code

Then add these rules to.babelrc:

	{
		"presets": [
			"es2015"."react"."stage-2"]."plugins": [...]. }Copy the code

Command line transcoding Babel -cli

Babel The babel-CLI tool is used for command line transcoding.

The installation command is as follows:

$ npm install --global babel-cli
Copy the code

The basic usage is as follows:

The result of transcoding is output to standard output
$ babel example.js

# Transcode the result to a file
The --out-file or -o argument specifies the output file
$ babel example.js --out-file compiled.js
# or
$ babel example.js -o compiled.js

# Transcode the entire directory
# --out-dir or -d specifies the output directory
$ babel src --out-dir lib
# or
$ babel src -d lib

The -s parameter generates the source map file
$ babel src -d lib -s
Copy the code

The above code is installed in the global environment, and there are two problems:

  1. If the project is to run, the global environment must have Babel, which means that the project is dependent on the environment.
  2. Babel is installed globally and does not support different versions of Babel for different projects.

The solution to the above problem is to install Babel-CLI in the project.

# install
$ npm install -save-dev babel-cli
Copy the code

Then, rewrite package.json.

{
  / /..."DevDependencies" : {" Babel - cli ":" ^6.0. 0"}, "scripts" : {" build ":" Babel SRC - d lib "},}Copy the code

To transcode, run the $NPM run build command.

Third, the Babel – node

The babel-CLI tool provides an ES6-supported REPl environment with a babel-node command. It supports all the functionality of Node’s REPL environment and can run ES6 code directly.

$ babel-node
> (x => x * 2)(1)
Copy the code

The babel-node command can run ES6 scripts directly. Put the above code into the script file es6.js and run it directly.

$ babel-node es6.js
2
Copy the code

Babel-node can also be installed in a project.

$ npm install --save-dev babel-cli
Copy the code

Then rewrite package.json.

{
		"scripts": {
			"script-name": "babel-node script.js"}}Copy the code

In the above code, babel-node is used instead of node, so script.js itself does not have to do any transcoding.

Fourth, the Babel – register

The babel-register module overwrites the require command, adding a hook to it. Thereafter, whenever files with.js,.jsx,.es, and.es6 are loaded using require, they are transcoded with Babel first.

$ npm install -save-dev babel-register
Copy the code

To use babel-Register, you must first load it.


require("babel-register");
require("./index.js");
Copy the code

Then there is no need to transcode index.js manually.

Note that babel-register will only transcode files loaded with the require command, not the current file. In addition, it is real-time transcoding, so it is only suitable for use in development environments.

Five, the Babel – core

If some code needs to be transcoded by calling Babel’s API, you need to use the Babel-core module.

The installation command is as follows:

$ npm install babel-core --saves
Copy the code

Babel-core can then be called from within the project.


var babel = require("babel-core");

// String transcoding
babel.transform('code(); ', options);
// => { code, map, ast}

// File transcoding (asynchronous)
babel.transformFile('filename.js', options, function(err, result) {
		result;  // => {code, map, ast}
});

// File transcoding (synchronization)
babel.transformFileSync('filename.js', options);
// => {code, map, ast}

// Babel AST transcoding
babel.transformFromAst(ast, code, options);
// => { code, map, ast }
Copy the code

IO /docs/ Usage /… .

Here’s an example.


var es6Code = 'let x = n => n + 1';
var es5Code = require('babel-core')
	.transform(es6Code, {
	presets: ['es2015']
})
.code
// '"use strict"; \n\nvar x = function x(n) {\n return n + 1; \n}; '
Copy the code

In the above code, the first argument to the transform method is a string identifying the ES6 code to be transformed, and the second argument is the configuration object for the transformation.

Sixth, the Babel – polyfill

By default, Babel converts new JavaScript syntax rather than new apis for global objects such as Iterator, Generator, Set, Maps, Proxy, Reflect, Symbol, Promise, etc. And some methods defined on global objects (such as object.assign) are not transcoded.

For example, ES6 adds the array. from method to Array objects. Babel does not transcode this method. If you want this method to work, you must use babel-polyfill to provide a spacer for the current environment.

The installation command is as follows:


$ npm install --save babel-polyfill
Copy the code

Then, in the script header, add the following code:


import 'babel-polyfill';
/ / or
require('babel-polyfill')
Copy the code

Vii. Browser environment

Babel can also be used in a browser environment. However, starting with Babel 6.0, the browser version is no longer available directly, but is built with a build tool. If you don’t have or don’t want to use the build tool, you can get it by installing the 5.x version of the Babel-Core module.

$ npm install babel-core@old
Copy the code

After running the above command, you can find the browser versions of Babel, browser.js and browser.min.js, in the node_modules/babel-core subdirectory of the current directory.

Then, insert the following code into the page:

<script src="node_modules/babel-core/browser.js"></script>
<script type="text/babel">
// Your ES6 code
</script>
Copy the code

In the above code, browser.js is a converter script provided by Babel that can be run in a browser. The user’s ES6 script is placed in the script tag, but type=”text/ Babel “.

Another approach is to use the version of the browser provided by the Babel-Standalone module and insert it into the web page.

<script src=" [https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.4.4/babel.min.js] (HTTP: / / https://cdnjs.cloudflare.com/ajax/libs/babe L - standalone / 6.4.4 Babel. Min. Js)"></script>
<script type="text/babel">
// Your ES6 code
</script>
Copy the code

Note: Converting ES6 code to ES5 in real time on a web page has a performance impact. The production environment needs to load scripts that have been transcoded.

Here’s how to package the code into a script that browsers can use, using Babel with Browserify as an example. First, install the Babelify module:

$ npm install --save-dev babelify babel-preset-es2015
Copy the code

Then, convert the ES6 script from the command line:

$ browserify script.js -o bundle.js \ -t [babelify --presets [ es2015 react] ]
Copy the code

The above code converts the ES6 script script.js to bundle.js, which the browser loads directly.

Set the following code in package.json so that you don’t have to enter arguments on the command line every time.


{
	"browserify": {
		"transform": [["babelify", {"presets": ["es2015"]]]}}}Copy the code

Eight, with other tools

Here are two examples: ESLint and Mocha.

ESLint statically checks the syntax and style of code. The installation command is as follows:

$ npm install --save-dev eslint babel-eslint
Copy the code

Next, create a new configuration file,.eslint, in the project root directory with the parser field.

{" parser ":" babel-eslint ", "rules" : {... }}Copy the code

In package.json, add the corresponding scripts.

{
    "name": "my-module"."scripts": {
      "lint": "eslint my-files.js"
    },
    "devDependencies": {
      "babel-eslint": "..."."eslint": "..."}}Copy the code

Mocha is a testing framework, and if you need to execute test scripts using ES6 syntax, you can modify package.json scripts.test.

"scripts": {
  "test": "Mocha -- UI QUnit -- Compilers JS: Babel-core/Register"
}
Copy the code

In the preceding command, the –compilers parameter specifies the script transcoder, and files with js suffix must be transcoded using babel-core/register first.