Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
  }

The code I am trying to work with is

src/index.js

require("babel-polyfill");

async function foo() {
  return 10;
}

and my 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 the build.js I get this error ReferenceError: regeneratorRuntime is not defined

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.

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

like image 912
Jatin Avatar asked Sep 02 '16 06:09

Jatin


People also ask

Do you need Babel polyfill?

So long story short, just using babel is not enough for your application to work because all the latest Javascript features are not supported in all browsers. So to fix this problem, we need to use a polyfill.

What can I use instead of Babel polyfill?

core-js is currently replacing bable-polyfill. You do not have to set it anywhere except for the . babelrc file I have a question, why do you duplicate libraries you have @babel/polyfill and babel-pollyfill the same applies to @babel/preset-env and babel-preset-en .

Does Babel automatically polyfill?

Babel includes a polyfill that includes a custom regenerator runtime and core-js. This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node ).

How does Babel polyfill work?

Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used.


2 Answers

Since functions defined such as

async function foo() {
    return 10;
}

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;
}
like image 170
Emmett Avatar answered Oct 05 '22 23:10

Emmett


I think that the require() call must come before the async function (and since functions are hoisted, and you set them up in the same file, the polyfill is loaded later).

Try to require('babel-polyfill') in an earlier stage in the module system. Something like this:

// A.js
require('babel-polyfill');
const foo = require('./B.js');

foo().then(console.log);

// B.js
async function foo() {
  return 10;
}

module.exports.foo = foo;
like image 41
Madara's Ghost Avatar answered Oct 05 '22 23:10

Madara's Ghost