javascript - Using async/await with babel - require("babel-polyfill") line not at the top in built file -


i trying use es2017 async/await syntax babel. in package.json, 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"   } 

the code trying work is

src/index.js

require("babel-polyfill");  async function foo() {   return 10; } 

and built file is

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"); 

while running build.js error referenceerror: regeneratorruntime not defined

however, in build.js, if move require("babel-polyfill"); line top, works. can't manually every time.

so, how use async/await syntax babel?

since functions defined such as

async function foo() {     return 10; } 

can used before they're defined in javascript, babel moving top of file during transpilation.

to work around this, try adjusting syntax if possible:

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

Comments