执行 Babel 生成的代码

    Babel 几乎可以编译所有时新的 JavaScript 语法,但对于 APIs 来说却并非如此。

    比方说,下列含有箭头函数的需要编译的代码:

    最终会变成这样:

    1. function addAll() {
    2. return Array.from(arguments).reduce(function(a, b) {
    3. return a + b;
    4. });
    5. }

    然而,它依然无法随处可用因为不是所有的 JavaScript 环境都支持 。

    1. Uncaught TypeError: Array.from is not a function

    Babel 用了优秀的 用作 polyfill,并且还有定制化的 regenerator 来让 generators(生成器)和 async functions(异步函数)正常工作。

    要使用 Babel polyfill,首先用 npm 安装它:

    然后只需要在文件顶部导入 polyfill 就可以了:

    1. import "babel-polyfill";

    babel-runtime

    为了实现 ECMAScript 规范的细节,Babel 会使用“助手”方法来保持生成代码的整洁。

    通过安装 babel-plugin-transform-runtime 和 来开始。

    1. $ npm install --save babel-runtime

    然后更新 .babelrc

    现在,Babel 会把这样的代码:

    1. class Foo {
    2. method() {}
    3. }

    编译成:

    1. import _classCallCheck from "babel-runtime/helpers/classCallCheck";
    2. import _createClass from "babel-runtime/helpers/createClass";
    3.  
    4. let Foo = function () {
    5. function Foo() {
    6. }
    7.  
    8. _createClass(Foo, [{
    9. key: "method",
    10. value: function method() {}
    11. }]);
    12.  
    13. return Foo;
    14. }();