执行 Babel 生成的代码
Babel 几乎可以编译所有时新的 JavaScript 语法,但对于 APIs 来说却并非如此。
比方说,下列含有箭头函数的需要编译的代码:
最终会变成这样:
- function addAll() {
- return Array.from(arguments).reduce(function(a, b) {
- return a + b;
- });
- }
然而,它依然无法随处可用因为不是所有的 JavaScript 环境都支持 。
Uncaught TypeError: Array.from is not a function
Babel 用了优秀的 用作 polyfill,并且还有定制化的 regenerator 来让 generators(生成器)和 async functions(异步函数)正常工作。
要使用 Babel polyfill,首先用 npm 安装它:
然后只需要在文件顶部导入 polyfill 就可以了:
- import "babel-polyfill";
babel-runtime
为了实现 ECMAScript 规范的细节,Babel 会使用“助手”方法来保持生成代码的整洁。
通过安装 babel-plugin-transform-runtime
和 来开始。
- $ npm install --save babel-runtime
然后更新 .babelrc
:
现在,Babel 会把这样的代码:
- class Foo {
- method() {}
- }
编译成:
- import _classCallCheck from "babel-runtime/helpers/classCallCheck";
- import _createClass from "babel-runtime/helpers/createClass";
- let Foo = function () {
- function Foo() {
- }
- _createClass(Foo, [{
- key: "method",
- value: function method() {}
- }]);
- return Foo;
- }();