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:
function addAll() {
return Array.from(arguments).reduce(function(a, b) {
return a + b;
});
}
However, this still won’t work everywhere because Array.from
doesn’t exist
in every JavaScript environment.
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:
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
:
$ npm install --save babel-runtime
Then update your .babelrc
:
Now Babel will compile code like the following:
class Foo {
method() {}
}
Into this:
import _classCallCheck from "babel-runtime/helpers/classCallCheck";
import _createClass from "babel-runtime/helpers/createClass";
function Foo() {
}
_createClass(Foo, [{
key: "method",
value: function method() {}
}]);
return Foo;
}();