About babel, you should know some of the things

Overview

babel itself is a tool, responsible for converting es6 / es7 es5 code into the code to run in modern browsers inside, more importantly, babel extension mechanism so that it can be converted jsx to React, do static syntax analysis for the Flow .

babel comprising various modules, convert it to a preset number of plug-ins by the code, we are going to talk about.

Note: Suppose you install a local node and npm, and does not exclude the use of command-line tools, while ensuring that your project file which contains pajkage.json;

babel-cli

Babel CLI command line to achieve the conversion code, you can install it by babel-cli -g global npm install, of course, also be performed npm install babel-cli -save-dev for local installation in the local project directory,

Here manner recommended items locally installed, mainly in the following two advantages:

1. Different versions of the project itself will be dependent on the babel of differences prevent the strong dependence;
2. the project itself dependent babel version can be any free and flexible management and control;

After completion of the project to install babel-cli-dependent, you can enter the following command in the console:

1
babel example.js --out-file compiled.js

Each instruction portion meanings:

  • babel call babel cli;
  • example.js specified the need to convert es6 / es7 file;
  • -out-file babel compiler option, on behalf of the compiled file output, can be abbreviated as -o, if you need to compile a catalog file, the outputs with -output-dir, may be abbreviated as -d;
  • compiled.js - Specifies the output file name;

Every change instruction complete code knock again, obviously it is a demanding task, we can build tasks by giving instructions to configure a package.json of scripts, to automate the steps of:

1
2
3
4
5
6
7
{
...
"scripts": {
"build": "babel ./src -d ./lib -w"
}
...
}

-W above instruction represents babel monitors file src directory changes, such as changes to recompile the code is executed and inputted to lib directory;

babel-register

babel-register by binding the node's require function, implemented by the hook-line transcoding function; in this way is not recommended for use in a production environment, due to the loss of real-time transcoder will bring performance and lead to poor experience, so the better way is to before deploying the code to complete the conversion code;

However, the development environment is still very easy to use, can be achieved directly compile and execute code, how that use babel-register it?
First need to install babel-register instruction by

1
npm install babel-register --save-dev

Create a simple es6 / es7 file index.js:

1
2
const sayHello = () => {console.log('hello')};
sayHello();

Create a new file to require index.js file register.js:

1
2
require('babel-register');
require('index.js');

When we run the node register.js, the console will output hello;

babel-node

If you want to quickly execute a need babel converted file, the best way is to use babel-node command, the same way is not recommended for use in a production environment, the same reasons, the installation of babel cli natural to carry a babel-node, how to use it?

First, create a simple es6 / es7 file index.js:

1
2
const sayHello = () => {console.log('hello')};
sayHello();

Next direct babel-node index.js, then you can see the output hello in the console;

Configuring Babel

As I said before, if you do not inform babel, babel ability will not do anything, except the file moved from one place to another, so we have to provide presets and plugins configured to inform the babel how to work babel.

.babelrc

.babelrc file is the configuration file babel, probably file structure as follows

1
2
3
4
{
"presets": [],
"plugins": []
}

Now suppose we want to inform babel will be a standards-based es6 React transcoded into es5 by babel configuration file, how to do?

  1. First we need to install the preset preset and React of es2015 of;
1
2
npm install babel-preset-es2015 --save-dev
npm install babel-preset-react --save-dev
  1. Update .babelrc, you can add a preset configuration;
1
2
3
4
{
"presets": ["es2015", "react"],
"plugins": []
}

That if our code files which use a lot of draft es6 stage (Draft) syntax, babel need to add additional what preset it is well known that a standard js norms need to go through five stages (Strawman, Proposal, Draft, Candidate, Finished ), will be included in the final standard, the final draft stage is likely inclusion criteria, babel preset by presetting various stages of completion of the appropriate conversion work, mainly in the following four:

  • babel-preset-stage-0
  • babel-preset-stage-1
  • babel-preset-stage-2
  • babel-preset-stage-3

The reason why no babel-preset-stage-5, because it is a babel-preset-es2015

Each of the above stage are dependent on it a preset after preset, e.g. babel-preset-stage-1 depends on babel-preset-stage-2, and babel-preset-stage-3

So to support the draft stage syntax as long as you install the corresponding preset,

1
npm install babel-preset-stage-2

Babel can then change the configuration file:

1
2
3
4
{
"presets": ["es2015", "react", "stage-2"],
"plugins": []
}

babel-polyfill

babel-polyfill es6 will simulate the entire environment, for example in the absence polyfill case, the following code:

1
2
3
function () {
return Array.from(arguments).map((a) => a + 2);
}

Converted to

1
2
3
4
5
function () {
return Array.from(argument).map(function (a) {
return a + 2;
});
}

This code actually does not work in many browsers (low version of qq browser, Baidu browser, etc.), because of their js kernel does not support Array.from api:

1
Uncaught TypeError: Array.from is not a function

To solve this problem, we need to add a polyfill, a polyfill itself is a fragment of code that implements the local api js current operating environment unrealized, babel using corejs as its polyfill, using regenerator support generators and async function;

To support babel polyfill function, you first need to install it:

1
npm install babel-polyfill --save-dev

Then reference the file at the top of any document of the need to use polyfill:

1
import 'babel-polyfill';

babel Advanced Configuration

A lot of people just use the built-babel some presets to complete some work, but the ability is actually far babel Not only that:

Manually configure the plugin

babel of presets itself is a series of preset plug-ins, if you want to add some special support, you can manually add additional plug-ins, for example, you want your code to support decorators es7, you just install the corresponding plug-decorators:

1
npm install babel-plugin-transform-decorators --save-dev

.Babelrc then added to the file can be:

1
2
3
4
{
"presets": ["es2015"],
"plugins": ["transform-decorators"]
}

你可以在babel官网查看babel 官方插件列表,你也可以在npm仓库查看开源社区贡献的babel插件列表

有些插件还可以额外添加一些配置项,例如很多插件会包含一个 “loose” 配置项用来指定 丢弃一些标准规范的行为,以便生成更简单,更健壮的代码;

1
2
3
4
5
{
...
plugins: ["transform-es2015-classes", { "loose": true }]
...
}

分环境配置babel

babel有很多插件提供了对开发过程中的支持,同时也有很多插件提供了对生产环境的代码优化,你可以通过指定不同环境动态加载不同的babel插件:

1
2
3
4
5
6
7
8
9
10
11
{
"presets": ["es2015"],
"env": {
"development": {
"plugins": [...]
},
"production": {
"plugins": [...]
}
}
}

当前的上下文环境是根据 process.env.BABEL_ENV 获取的,若没有,则尝试从 process.env.NODE_ENV 获取,若NODE_ENV也没有,则默认是 development 环境;

以下是分别在Unix和Windows系统上设置环境变量的方式:

Unix:

1
2
$ BABEL_ENV=development
$ NODE_ENV=development

Windows:

1
2
$ SET BABEL_ENV=development
$ SET NODE_ENV=development

当然更好的方式是使用类似cross-env的npm 包,它可以让你通过脚本参数指定环境变量。

构建自己的babel配置

每次写相同的babel配置文件其实很浪费时间,所以我们需要构建自己的presets模块

假设有如下的 .babelrc

1
2
3
4
{
"presets": ["es2015", "react"],
"plugins": ["transform-decorators"]
}

接下来你要做的就是命名该项目 babel-preset-* ,然后创建两个文件:
一个 package.json 文件:

1
2
3
4
5
6
7
8
9
10
{
"name": "babel-preset-awesome",
"version": "1.0.0",
"author": "Kliment Petrov <[email protected]> (http://kleopetrov.me)",
"dependencies": {
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-plugin-transform-decorators": "^6.6.5",
}
}

然后,创建一个 index.js 文件并导出 .babelrc 的上下文,将文件中的preset和插件改为用require的方式调用:

1
2
3
4
5
6
7
8
9
10
11
module.exports {
{
presets: [
require("es2015"),
require("react")
],
plugins: [
require("transform-decorators")
]
}
}

最后将它发布到npm仓库即可;

其它工具

babel也可以和其它工具例如 linting,代码风格 配合一起使用

Linting

最有名的Linting工具非eslint莫属,babel将其整合到官方支持,首先,我们需要安装对应的包:

1
npm install eslint babel-eslint --save-dev

接下来,在你的项目下创建 .eslintrc 文件,并做配置:

1
2
3
4
5
6
{
"parser": "babel-eslint",
"rules": {
...
}
}

The last configuration script lint in your package.json, and then perform npm run lint can:

1
2
3
4
5
6
7
{
...
"scripts": {
"lint": "eslint ./src/*.js*"
}
...
}

Editor plug-in

As more and more users babel, major ide also provides a corresponding plug-in support babel

to sum up

babel and its surrounding ecology web development play an increasingly important role in today, through the introduction of this article, you can use the latest technology and the surrounding js specification by configuring enjoy (JSX, Flow, etc.), then Not much to say, hurry to start it!

Original: Large columns  on babel, you should know some of the things


Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11618430.html