I'm trying to use async, await from scratch on Babel 6, but I'm getting regeneratorRuntime is not defined.
.babelrc file
{
"presets": [ "es2015", "stage-0" ]
}
package.json file
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js file
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?
I fixed this error by installing babel-polyfill
then I imported it in my app entry point
for testing I included --require babel-polyfill in my test script
If you using Gulp + Babel for a frontend you need to use babel-polyfill
npm install babel-polyfill
and then add a script tag to index.html above all other script tags and reference babel-polyfill from node_modules
Be careful of hoisted functions
I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the
ReferenceError: regeneratorRuntime is not defined
error.Change this code
to this
to prevent it being hoisted above the polyfill import.
Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:
It also includes support for async/await along with other built-ins of ES 6.
In
.babelrc
, add the runtime pluginFor people looking to use the
babel-polyfill
version 7^ do this withwebpack
ver3^.Npm install the module
npm i -D @babel/polyfill
Then in your
webpack
file in yourentry
point do thisYou're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (
npm install --save babel-preset-es2016
) and compile to ES2016 instead of ES2015:As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.