Executing Babel-generated code

    Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs.

    For example, the following code has an arrow function that needs to be compiled:

    Which turns into this:

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

    However, this still won’t work everywhere because Array.from doesn’t exist in every JavaScript environment.

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

    Babel uses the excellent as its polyfill, along with a customized regenerator runtime for getting generators and async functions working.

    To include the Babel polyfill, first install it with npm:

    Then simply include the polyfill at the top of any file that requires it:

    1. import "babel-polyfill";

    In order to implement details of ECMAScript specs, Babel will use “helper” methods in order to keep the generated code clean.

    Start by installing babel-plugin-transform-runtime and babel-runtime:

    1. $ npm install --save babel-runtime

    Then update your .babelrc:

    Now Babel will compile code like the following:

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

    Into this:

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