通过babel使用async/await-require("babel-polyfill")行不在构建文件的顶部 [英] Using async/await with babel - require("babel-polyfill") line not at the top in built file

查看:345
本文介绍了通过babel使用async/await-require("babel-polyfill")行不在构建文件的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Babel使用ES2017异步/等待语法. 在package.json中,我有

I am trying to use ES2017 async/await syntax with Babel. In package.json, I have

"babel": {
    "plugins": [
      "babel-plugin-transform-async-to-generator"
    ],
    "presets": [
      "es2015"
    ]
  }

//...

"devDependencies": {
    "babel-cli": "^6.14.0",
    "babel-plugin-transform-async-to-generator": "^6.8.0",
    "babel-polyfill": "^6.13.0",
    "babel-preset-es2015": "^6.14.0"
  }

我要使用的代码是

src/index.js

require("babel-polyfill");

async function foo() {
  return 10;
}

我的构建文件是

dist/build.js

"use strict";

var foo = function () {
  var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            return _context.abrupt("return", 10);

          case 1:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function foo() {
    return _ref.apply(this, arguments);
  };
}();

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { return step("next", value); }, function (err) { return step("throw", err); }); } } return step("next"); }); }; }

require("babel-polyfill");

运行 build.js 时出现此错误 ReferenceError: regeneratorRuntime is not defined

但是,在 build.js 中,如果将require("babel-polyfill");行移到顶部,则可以正常工作.但是我不能每次都手动进行操作

However, in the build.js, if I move the require("babel-polyfill"); line to the top, it works. But I can't manually do that every time.

那么,如何在babel中使用async/await语法?

So, how to do I use the async/await syntax with babel?

推荐答案

自定义函数以来,例如

async function foo() {
    return 10;
}

可以在使用之前使用在javascript中定义,Babel会在编译过程中将其移至文件顶部.

can be used before they're defined in javascript, Babel is moving it to the top of the file during transpilation.

要解决此问题,请尝试尝试调整语法:

To work around this, this try adjusting your syntax if possible:

const foo = async function() {
    return 10;
}

这篇关于通过babel使用async/await-require("babel-polyfill")行不在构建文件的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆