Blog A Paranoid Guy

Babel入坑须知

2016-07-27

自从 Babel 由版本5升级到版本6后,在安装和使用方式上与之前大相径庭,于是写了这篇入坑须知,以免被新版本所坑。


坑一:本地安装和全局安装

全局安装只需:

   $ npm install --global babel-cli

这时候我们可以使用 Babel 命令编译文件:

    $ babel index.js --out-file compiled.js
    #或
    $ babel index.js -o compiled.js

编译目录:

    $ babel src -out-dir lib
    #或
    babel src -d lib

但是,官方推荐本地安装,是这么说的:

While you can install Babel CLI globally on your machine, it’s much better to install it locally project by project.

There are two primary reasons for this.

  1. Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time.

  2. It means you do not have an implicit dependency on the environment you are working in. Making your project far more portable and easier to setup.

大致的意思就是:可移植性较好并且没有依赖。

本地安装,记在项目的根目录下:

    $ npm install --save-dev bable-cli

但是在本地就不能用 bable 命令了,我们可以在 package.json 文件中添加点东西:

    {
        "script": {
            "build": "babel src -d lib"
        }
    }

然后,运行 npm run build 即可把 src 目录编译输出到 lib


坑二: 编译插件

上述编译其实并没有进行,而是原样输出。这是因为我们没有安装相应的插件,官方提示我们需要安装 babel-reset-es2015 插件:

    $ npm install --save-dev babel-preset-es2015

然后,在根目录创建一个名为 .babelrc 的文件,里面配置如下内容:

    {
        "presets": [
            "es2015"
        ]
    }

同理,可以设置 React 的编译插件:

    $ npm install --save-dev babel-preset-react

.babelrc 文件里即:

    {
       "presets": [
           "es2015",
           "react"
       ] 
    }

坑三: babel-polyfill插件

Babel 默认只转换新的 JavaScript 句法(syntax),而不转换新的 API ,比如 IteratorGeneratorSetMapsProxyReflectSymbolPromise 等全局对象,以及一些定义在全局对象上的方法(比如 Object.assign)都不会转码。Babel 默认不转码的 API 非常多,详细清单可以查看 definitions.js 文件

为了完整使用 ES6API ,我们只能安装这个插件:

    $ npm install -save-dev babel-polyfill

然后,在需要使用的文件的顶部引入

    import "babel-polyfill"

node.js 中:

    require('babel-polyfill');

webpack.config.js 中:

    module.exports = {
        entry: ['babel-polyfill', './app/js']
    }

参考资料

Babel官网

Babel使用指南

ES6标准入门@阮一峰


下一篇 Node.js--URL模块

Comments