• Executing Babel-generated code
    • babel-polyfill
    • babel-runtime

    Executing Babel-generated code

    So you’ve compiled your code with Babel, but this is not the end of the story.

    babel-polyfill

    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:

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

    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

    To solve this problem we use something called a Polyfill. Simply put, a polyfill is a piece of code that replicates a native api that does not exist in the current runtime. Allowing you to use APIs such as Array.from before they are available.

    Babel uses the excellent core-js 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:

    1. $ npm install --save babel-polyfill

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

    1. import "babel-polyfill";

    babel-runtime

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

    Since these helpers can get pretty long, and they get added to the top of every file you can move them into a single “runtime” which gets required.

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

    1. $ npm install --save-dev babel-plugin-transform-runtime
    2. $ npm install --save babel-runtime

    Then update your .babelrc:

    1. {
    2. "plugins": [
    3. + "transform-runtime",
    4. "transform-es2015-classes"
    5. ]
    6. }

    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. let Foo = function () {
    4. function Foo() {
    5. _classCallCheck(this, Foo);
    6. }
    7. _createClass(Foo, [{
    8. key: "method",
    9. value: function method() {}
    10. }]);
    11. return Foo;
    12. }();

    Rather than putting the _classCallCheck and _createClass helpers in every single file where they are needed.