Babel introductory tutorial
(Note: This article is selected from the first chapter “Introduction to ECMAScript 6” of my new book “Introduction to ES6 Standards (Second Edition) ” )
Babel is a widely used transcoder that can convert ES6 code to ES5 code for execution in the existing environment.
This means that you can write programs in ES6 now without worrying about whether the existing environment supports it. Below is an example.
// 转码前 input.map(item => item + 1); // 转码后 input.map(function (item) { return item + 1; });
The original code above uses arrow functions. This feature has not been widely supported. Babel converts it to a normal function and can be executed in the existing JavaScript environment.
One, configuration file
.babelrc
Babel’s configuration file is
.babelrc
stored in the root directory of the project.
The first step in using Babel is to configure this file.
This file is used to set transcoding rules and plug-ins. The basic format is as follows.
{ "presets": [], "plugins": [] }
presets
The field sets the transcoding rules, the official provides the following rule sets, you can install them according to your needs.
# ES2015转码规则 $ npm install --save-dev babel-preset-es2015 # react转码规则 $ npm install --save-dev babel-preset-react # ES7不同阶段语法提案的转码规则(共有4个阶段),选装一个 $ 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-3
Then, add these rules
.babelrc
.
{ "presets": [ "es2015", "react", "stage-2" ], "plugins": [] }
Note that all the following Babel tools and modules must be written first
.babelrc
.
Two, command line transcoding
babel-cli
Babel provides
babel-cli
tools for command line transcoding.
Its installation command is as follows.
$ npm install --global babel-cli
The basic usage is as follows.
# 转码结果输出到标准输出 $ babel example.js # 转码结果写入一个文件 # --out-file 或 -o 参数指定输出文件 $ babel example.js --out-file compiled.js # 或者 $ babel example.js -o compiled.js # 整个目录转码 # --out-dir 或 -d 参数指定输出目录 $ babel src --out-dir lib # 或者 $ babel src -d lib # -s 参数生成source map文件 $ babel src -d lib -s
The above code is for Babel transcoding in the global environment. This means that if the project is to run, the global environment must have Babel, which means that the project has a dependency on the environment. On the other hand, this does not support the use of different versions of Babel for different projects.
One solution is to
babel-cli
install it in the project.
# 安装 $ npm install --save-dev babel-cli
Then, rewrite
package.json
.
{ // ... "devDependencies": { "babel-cli": "^6.0.0" }, "scripts": { "build": "babel src -d lib" }, }
When transcoding, execute the following command.
$ npm run build
Three, babel-node
babel-cli
The tool comes with a
babel-node
command to provide a REPL environment that supports ES6.
It supports all the functions of Node’s REPL environment and can run ES6 code directly.
It does not need to be installed separately, but is
babel-cli
installed together.
Then, the execution
babel-node
enters the PEPL environment.
$ babel-node > (x => x * 2)(1) 2
babel-node
Commands can run ES6 scripts directly.
Put the above code into a script file
es6.js
and run it directly.
$ babel-node es6.js 2
babel-node
It can also be installed in the project.
$ npm install --save-dev babel-cli
Then, rewrite
package.json
.
{ "scripts": { "script-name": "babel-node script.js" } }
In the above code,
babel-node
replace is
used
node
, so
script.js
that there is no need to do any transcoding processing itself.
Four, babel-register
babel-register
The module rewrites the
require
command and adds a hook to it.
Since then, whenever the
require
load
.js
,
.jsx
,
.es
and
.es6
file extension, it will first be transcoded with Babel.
$ npm install --save-dev babel-register
When used, it must be loaded first
babel-register
.
require("babel-register"); require("./index.js");
Then, there is no need to manually
index.js
transcode.
It should be noted that
babel-register
only
require
the file loaded by
the
command will be transcoded, not the current file.
In addition, since it is real-time transcoding, it is only suitable for use in a development environment.
Five, babel-core
If some code needs to call Babel’s API for transcoding, it is necessary to use a
babel-core
module.
The installation command is as follows.
$ npm install babel-core --save
Then, it can be called in the project
babel-core
.
var babel = require('babel-core'); // 字符串转码 babel.transform('code();', options); // => { code, map, ast } // 文件转码(异步) babel.transformFile('filename.js', options, function(err, result) { result; // => { code, map, ast } }); // 文件转码(同步) babel.transformFileSync('filename.js', options); // => { code, map, ast } // Babel AST转码 babel.transformFromAst(ast, code, options); // => { code, map, ast }
For configuration objects
options
, please refer to the official document
http://babeljs.io/docs/usage/options/
.
Below is 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};'
In the above code,
transform
the first parameter of the method is a string, indicating the ES6 code that needs to be converted, and the second parameter is the configuration object to be converted.
Six, babel-polyfill
By default, Babel only converts new JavaScript syntax (syntax), and does not convert new APIs, such as Iterator, Generator, Set, Maps, Proxy, Reflect, Symbol, Promise and other global objects, as well as some methods defined on global objects (such as
Object.assign
) Will not transcode.
For example, ES6
Array
adds new
Array.from
methods to
objects
.
Babel will not transcode this method.
If you want this method to work, you must use
babel-polyfill
it to provide a shim for the current environment.
The installation command is as follows.
$ npm install --save babel-polyfill
Then, at the head of the script, add the following line of code.
import 'babel-polyfill'; // 或者 require('babel-polyfill');
There are many APIs that Babel does not transcode by default
.
You can check
babel-plugin-transform-runtime
the
definitions.js
file of the
module for a
detailed list
.
Seven, browser environment
Babel can also be used in a browser environment.
However, starting from Babel 6.0, the browser version is no longer provided directly, but to be 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
After running the above command, you can
node_modules/babel-core/
find
babel
the browser version
browser.js
(not streamlined) and
browser.min.js
(streamlined)
in the
subdirectories of the
current directory
.
Then, insert the following code into the web page.
<script src="node_modules/babel-core/browser.js"></script> <script type="text/babel"> // Your ES6 code </script>
The above code
browser.js
is the converter script provided by Babel, which can be run in the browser.
The user’s ES6 script is placed in the
script
label, but it should be noted
type="text/babel"
.
Another method is to use the browser version 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"></script> <script type="text/babel"> // Your ES6 code </script>
Note that the real-time conversion of ES6 code to ES5 in the web page will have an impact on performance. The production environment needs to load the script that has been transcoded.
The following is how to package the code into a script that can be used by the browser, taking
Babel
cooperation
Browserify
as an example.
First, install the
babelify
module.
$ npm install --save-dev babelify babel-preset-es2015
Then, use the command line to convert the ES6 script.
$ browserify script.js -o bundle.js \ -t [ babelify --presets [ es2015 react ] ]
The above code converts the ES6 script
script.js
to
bundle.js
, and the browser loads the latter directly.
When
package.json
setting the code below, there is no need to enter parameters every time on the command line.
{ "browserify": { "transform": [["babelify", { "presets": ["es2015"] }]] } }
Eight, online conversion
Babel provides a REPL online compiler that can convert ES6 code to ES5 code online. The converted code can be directly inserted into the webpage and run as ES5 code.
Nine, coordination with other tools
Many tools require Babel for pre-transcoding. Here are two examples: ESLint and Mocha.
ESLint is used to statically check the syntax and style of the code. The installation commands are as follows.
$ npm install --save-dev eslint babel-eslint
Then, in the project root directory, create a new configuration file
.eslint
and add
parser
fields to it.
{ "parser": "babel-eslint", "rules": { ... } }
In the
package.json
middle, add the corresponding
scripts
script.
{ "name": "my-module", "scripts": { "lint": "eslint my-files.js" }, "devDependencies": { "babel-eslint": "...", "eslint": "..." } }
Mocha
is a testing framework, you need to perform a test script using ES6 syntax, you can modify
package.json
the
scripts.test
.
"scripts": { "test": "mocha --ui qunit --compilers js:babel-core/register" }
In the above command, the
--compilers
parameter specifies the transcoder of the script, and
js
the file with the
specified suffix name
needs to
babel-core/register
be transcoded first.
(over)