825

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
BrunoLM
  • 97,872
  • 84
  • 296
  • 452

48 Answers48

757

babel-polyfill (deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.

npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader

package.json

"devDependencies": {
  "babel-core": "^6.0.20",
  "babel-polyfill": "^6.0.16",
  "babel-preset-es2015": "^6.0.15",
  "babel-preset-stage-0": "^6.0.15"
}

.babelrc

{
  "presets": [ "es2015", "stage-0" ]
}

.js with async/await (sample code)

"use strict";

export default async function foo() {
  var s = await bar();
  console.log(s);
}

function bar() {
  return "bar";
}

In the startup file

require("babel-core/register");
require("babel-polyfill");

If you are using webpack you need to put it as the first value of your entry array in your webpack configuration file (usually webpack.config.js), as per @Cemen comment:

module.exports = {
  entry: ['babel-polyfill', './test.js'],

  output: {
    filename: 'bundle.js'       
  },

  module: {
    loaders: [
      { test: /\.jsx?$/, loader: 'babel', }
    ]
  }
};

If you want to run tests with babel then use:

mocha --compilers js:babel-core/register --require babel-polyfill
Lemmings19
  • 1,383
  • 3
  • 21
  • 34
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 83
    Important when you are using babel with webpack: rather than using `require("babel-polyfill")` which is not working, you add `"babel-polyfill"` into your `entry` in config, like this: `entry: ["babel-polyfill", "src/main.js"]`. This worked for me, including use in webpack-dev-server with HMR. – Cemen Nov 21 '15 at 11:28
  • 6
    I was trying to get my mocha tests to run with babel6 and async and I had to add --require babel-polyfill to the npm test runner configuration – arisalexis Dec 14 '15 at 11:23
  • 13
    What's babel-register for? – trusktr Feb 09 '16 at 00:33
  • I am using webpack. For me, import "babel-polyfill" at the top of my entry file(app.js, for example) works, I do not need to add babel-polyfill in the entry option in my webpack config – Alan Feb 12 '16 at 16:49
  • 1
    shouldn't babel-polyfill be a dependency, not a devDependency? – Lloyd Feb 26 '16 at 16:18
  • 6
    @Lloyd `devDependency` if you are using webpack because it will then "compile" the files before running. `dependency` if you are not using webpack and you are requiring babel. – BrunoLM Feb 26 '16 at 20:20
  • What would gulpfile.babel.js look like? – anon Mar 04 '16 at 09:16
  • 1
    @trusktr Just figured this out. It hooks into node's require statement meaning `require`s can transpile ES6 code. Also causes your stack traces to double up as each require will go through the ES6 transpiling code. I'm guessing this probably shouldn't be used for production. – Ally Apr 23 '16 at 16:52
  • 5
    This makes the output file size huge... Better to use only what you need instead of requiring babel-polyfill directly. – Inanc Gumus Jun 08 '16 at 19:37
  • 2
    Any advice for us not lucky enough to be in a webpack environment? I tried adding the two require statements to a gulpfile, that does the transpilation but regeneratorRuntime is still undefined. – Andrew Allbright Aug 30 '16 at 18:47
  • Thanks for this! I was looking all over how to do apply it as a mocha option. – Naoto Ida Nov 11 '16 at 09:23
  • 2
    If you use multiple entry points in webpack, you can also put babel-polyfill into one of them, as long as it's loaded first. In my case, i have one called "vendor" so my webpack.config.js looks like this: `entry: { app: './src/app.js', vendor: [ 'babel-polyfill', 'react' ] }` – Doug Mar 03 '17 at 16:46
  • Thanks; this in combination with `babel-runtime` as instructed bellow by @chrisjlee worked like a charm :) – Neil Mar 26 '17 at 08:58
  • 1
    [sarcasm]Yes of course `Uncaught ReferenceError: regeneratorRuntime is not defined` is such a clear message as to what the problem is.[/sarcasm] – RyanNerd Nov 14 '17 at 18:32
  • 1
    Check johnny answer about babel-plugin-transform-runtime https://babeljs.io/docs/en/babel-plugin-transform-runtime – Alex Pogiba Nov 02 '18 at 08:04
  • Side note... the `babel-preset-es2015` got my attention... I don't have that in my project and didn't want to add it (since the latest is now 2018). I see the OP had it, that's fine. I just left it out and things worked for me. My solution was much simpler than this answer. 1) I added babel-polyfill with `yarn add --dev babel-polyfill` 2) I updated the webpack entry to be `entry: ['babel-polyfill', './test.js'],` Then it worked. – Jason Feb 02 '19 at 19:23
  • 2
    I'm not using webpack so don't have a startup file. What's the answer then? – Batman Feb 19 '19 at 03:25
  • 1
    if you are using babel 7 which name has changed to "@babel/polyfill", please keep the same name in the config file as below: " entry: ['@babel/polyfill', './src/server/server.js'], " – ukalpa Apr 12 '19 at 17:38
  • as Daniel said polyfill is been deprecated but I getting error regarding babel <7.4 cannot find it, after I have installed only core3. Since 6 months I started to use webpack extensively it already changed so much, making quite impossible keep update with new terminology and way to use plugings. I found this very improductive – Carmine Tambascia Aug 31 '19 at 11:42
  • 1
    Just thought I'd add, with Babel 7 the imports are: `require("@babel/register");` `require("@babel/polyfill");` – aggregate1166877 Sep 28 '19 at 00:19
  • This is deprecated, use the plugin `@babel/plugin-transform-runtime` in your babel config as recommended on https://stackoverflow.com/a/61211001/2494611 – DrWaky Jul 14 '22 at 03:15
  • I had an old `babel-core` installed alongside the newer `@babel/core` which was causing this problem. https://stackoverflow.com/questions/53380741 – Sam Barnum Oct 07 '22 at 20:47
439

Note If you're using babel 7, the package has been renamed to @babel/plugin-transform-runtime.

Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:

Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.

It also includes support for async/await along with other built-ins of ES 6.

$ npm install --save-dev babel-plugin-transform-runtime

In .babelrc, add the runtime plugin

{
  "plugins": [
    ["transform-runtime", {
      "regenerator": true
    }]
  ]
}
Jahanzaib Aslam
  • 2,731
  • 3
  • 21
  • 26
johnny
  • 5,077
  • 1
  • 16
  • 9
  • 11
    I did not need `babel-runtime` to get async await working. Is that correct? Edit: I'm running the code server side. :) – GijsjanB Jul 26 '16 at 06:54
  • Thanks so much. That works very well on both server side and client side. In addintion, I don't need `babel-runtime`. – An Nguyen Sep 20 '16 at 15:00
  • 7
    I also only had to install `babel-plugin-transform-runtime` (no `babel-runtime`). - I believe this is the cleanest (more lightweight) solution for Webpack generated bundles. – Marco Lazzeri Oct 28 '16 at 14:52
  • 9
    If you were able to use it without babel-runtime, it's because it's already in your dependency tree. So be aware that if you're writing a library, and babel-runtime is coming in as a dev dependency, it might not be there for your users. You will have to include it as a normal dependency for distribution. – neverfox Nov 01 '16 at 21:55
  • 29
    only `babel-plugin-transform-runtime` required. Works like a charm. – saike Dec 19 '16 at 16:38
  • I was pulling my remaining hairs out over this. `babel-preset-env` did not work for me, this did after I added the plugin options (`regenerator`, etc) as suggested. – Mario Tacke Jan 13 '17 at 22:47
  • 14
    This solution is not OK because it requires an extra Browserify or Webpack job to expand the `require` calls that are added by the `transform-runtime` plugin. – Finesse Apr 19 '17 at 03:46
  • 1
    If you're going to try, this is the simplest and it works. ```babel-runtime``` is not needed, which makes it even simpler. – Kevin Le - Khnle Dec 21 '17 at 22:33
  • 4
    This is what finally worked for me. This is so incredibly frustrating; this should all be turnkey. Thank you. – duma Jan 16 '18 at 04:15
  • 2
    guys, this solution seems legit, but is there a way we can have a "sample" like what webpack looks like, what babelrc looks like.... in order to compile es6 for browser or launch the source with babel? I mean everytime i add a dependency another crashes... i'm a bit lost now – gropapa Mar 10 '18 at 23:24
  • At least it fixes the error: `Error: only one instance of babel-polyfill is allowed` when trying to include a js library that uses polyfill in a website that already uses it – Alcalyn Mar 14 '18 at 14:10
  • 23
    Note that for Babel 7 you need to run `npm install --save-dev @babel/plugin-transform-runtime` – Andrey Semakin Dec 30 '18 at 07:46
  • I get this error: `Uncaught Error: Module name "babel-runtime/helpers/slicedToArray" has not been loaded yet for context: _. Use require([])` – daCoda Jan 19 '20 at 23:41
  • 2
    Using `npm i -D @babel/plugin-transform-runtime` worked for me, FYI - in the `.babelrc` remember to change `transform-runtime` to `@babel/transform-runtime` – Chris Hayes Mar 07 '22 at 14:50
337

Babel 7 Users

I had some trouble getting around this since most information was for prior babel versions. For Babel 7, install these two dependencies:

npm install --save @babel/runtime 
npm install --save-dev @babel/plugin-transform-runtime

And, in .babelrc, add:

{
    "presets": ["@babel/preset-env"],
    "plugins": [
        ["@babel/transform-runtime"]
    ]
}
Matt Shirley
  • 4,216
  • 1
  • 15
  • 19
  • How we can do it without .babelrc (just using webpack config file) – Pouya Jabbarisani Jan 24 '19 at 13:29
  • Thanks! this works. What is the security/production implication of having @babel/runtime as a dependency instead of a devDependency? – newbreedofgeek Feb 01 '19 at 03:55
  • @newbreedofgeek Good question... I second guessed my answer! It's recommended by Babel. Check out https://babeljs.io/docs/en/babel-plugin-transform-runtime for an explanation. I'm not sure of the immediate implications. – Matt Shirley Feb 01 '19 at 07:06
  • 9
    The doc shows the usage as `"plugins": ["@babel/plugin-transform-runtime"]`, rather than the `"plugins": [ ["@babel/transform-runtime"] ]` here. Different plugin name. Both works. But which one is the proper one?.. – kyw Feb 02 '19 at 10:55
  • 15
    I get require is not defined when following this method – Batman Feb 19 '19 at 03:29
  • 1
    @kyw best to always follow the docs - no difference other than convention. – Matt Shirley Feb 19 '19 at 17:34
  • 6
    Adding `@babel/transform-runtime` to plugins caused "exports is not defined" error for me. I changed it to this to get async to work in Babel7 : `["@babel/plugin-transform-runtime", { "regenerator": true } ] ` – Hari Feb 28 '19 at 23:46
  • This helped get it working for me: https://github.com/babel/babel/issues/8829#issuecomment-456524916 – Dave Kiss Mar 30 '19 at 16:17
  • this is out of date, see the updated answer at https://stackoverflow.com/a/54490329/13195 – jes5199 Sep 16 '19 at 17:37
  • 1
    I'm using Babel 7.4.4 and this answer worked for me. – Ryan Shillington Sep 23 '20 at 16:31
122

Update

It works if you set the target to Chrome. But it might not work for other targets, please refer to: https://github.com/babel/babel-preset-env/issues/112

So this answer is NOT quite proper for the original question. I will keep it here as a reference to babel-preset-env.

A simple solution is to add import 'babel-polyfill' at the beginning of your code.

If you use webpack, a quick solution is to add babel-polyfill as shown below:

entry: {
    index: ['babel-polyfill', './index.js']
}

I believe I've found the latest best practice.

Check this project: https://github.com/babel/babel-preset-env

yarn add --dev babel-preset-env

Use the following as your babel configuration:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 Chrome versions"]
      }
    }]
  ]
}

Then your app should be good to go in the last 2 versions of Chrome browser.

You can also set Node as the targets or fine-tune the browsers list according to https://github.com/ai/browserslist

Tell me what, don't tell me how.

I really like babel-preset-env's philosophy: tell me which environment you want to support, do NOT tell me how to support them. It's the beauty of declarative programming.

I've tested async await and they DO work. I don't know how they work and I really don't want to know. I want to spend my time on my own code and my business logic instead. Thanks to babel-preset-env, it liberates me from the Babel configuration hell.

Tyler Liu
  • 19,552
  • 11
  • 100
  • 84
  • 3
    This really works. The only downside is a bunch of dependencies pulled by `babel-preset-env` but I think it's worth it. Love the declarative style too. Also `yarn install` is now `yarn add` – Roman Usherenko Jan 05 '17 at 22:32
  • @RomanUsherenko I've changed `yarn install` to `yarn add`. Thank you. – Tyler Liu Jan 06 '17 at 01:27
  • Does this replace the need for es2015 and stage-0 in presets? – gargantuan May 04 '17 at 13:15
  • 1
    @gargantuan Yes it does. – Tyler Liu May 04 '17 at 13:18
  • 3
    Not really a solution if you *want* to target older browsers or node versions. – Rohan Orton Oct 16 '17 at 08:47
  • Misleading answer. I was targeting Node `v.4` on Babel via Rollup, and also already using `babel-preset-env` and still getting this error.. What did help to solve `regeneratorruntime` error was adding `babel-plugin-transform-runtime` (only that, to plugins) as per @johnny answer. – revelt Dec 18 '17 at 00:30
  • 3
    Just in case it is not obvious.... this recommended solution will NOT work if you need your code to work in IE11 – Maurice Dec 24 '17 at 06:40
  • @RohanOrton `babel-preset-env` can indeed target older browsers and node versions. – Jonny Asmar Jan 08 '18 at 21:20
  • My latest attempt is `["env", { "targets": { "browsers": ["> 3%", "last 2 Chrome versions", "not ie <= 9", "Firefox ESR"] }, "useBuiltIns": true }]`, since the browsers support is very limited, if only use `"last 2 Chrome versions"` – FisNaN Apr 11 '18 at 04:07
  • You are the God of the universe! Also, I think it should be quite obvious if you want it to work on other browsers, add them to the targets array. – Shanerk Apr 13 '18 at 20:04
  • 15
    Why does this have so many up votes? This only works because it no longer transforms async/await and thus no longer needs the regeneratorRuntime and because it's not transformed it will not work on browsers that don't support it. – Shikyo Jun 09 '18 at 16:38
  • @Shikyo The answer did mention babel-polyfill at the very beginning which will make it work on old browsers. – Tyler Liu Jun 11 '18 at 07:03
  • https://esausilva.com/2017/07/11/uncaught-referenceerror-regeneratorruntime-is-not-defined-two-solutions/ has a pretty good article explaining how to fix this problem – Alfrex92 Oct 18 '18 at 14:37
92

Update: The Babel 7 post also has a more in-depth answer.


Babel 7.4.0 or later (core-js 2 / 3)

As of Babel 7.4.0, @babel/polyfill is deprecated.

In general, there are two ways to install polyfills/regenerator: via global namespace (Option 1) or as ponyfill (Option 2, without global pollution).


Option 1: @babel/preset-env

presets: [
  ["@babel/preset-env", {
    "useBuiltIns": "usage",
    "corejs": 3, // or 2,
    "targets": {
        "firefox": "64", // or whatever target to choose .    
    },
  }]
]

will automatically use regenerator-runtime and core-js according to your target. No need to import anything manually. Don't forget to install runtime dependencies:

npm i --save regenerator-runtime core-js

Alternatively, set useBuiltIns: "entry" and import it manually:

import "regenerator-runtime/runtime";
import "core-js/stable"; // if polyfills are also needed

Option 2: @babel/transform-runtime with @babel/runtime

This alternative has no global scope pollution and is suitable for libraries.

{
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true,
        "corejs": 3 // or 2; if polyfills needed
        ...
      }
    ]
  ]
}
Install it:
npm i -D @babel/plugin-transform-runtime
npm i @babel/runtime

If corejs polyfill is used, you replace @babel/runtime with @babel/runtime-corejs2 (for "corejs": 2) or @babel/runtime-corejs3 (for "corejs": 3).

ford04
  • 66,267
  • 20
  • 199
  • 171
  • 6
    { "presets": [ [ "@babel/preset-env", { "targets": { "esmodules": true } } ] ] } This has helped me for a node.js build – Smolin Pavel Aug 19 '19 at 21:33
  • 3
    I mean I knew that already but to help others this should be the correct answer. Best Regards! – pablito91 Aug 29 '19 at 13:45
  • 1
    Just a note that you should use `@babel/runtime-corejs2` or `@babel/runtime-corejs3` if using the `corejs` option with a value of `2` or `3` respectively. This is mentioned in the docs: https://babeljs.io/docs/en/babel-plugin-transform-runtime#corejs – Robin-Hoodie Jul 14 '20 at 09:14
  • 1
    Thanks @Robin-Hoodie, I updated last section of the answer to be a bit more clear on this topic. – ford04 Jul 14 '20 at 09:28
57

Alternatively, if you don't need all the modules babel-polyfill provides, you can just specify babel-regenerator-runtime in your webpack config:

module.exports = {
  entry: ['babel-regenerator-runtime', './test.js'],

  // ...
};

When using webpack-dev-server with HMR, doing this reduced the number of files it has to compile on every build by quite a lot. This module is installed as part of babel-polyfill so if you already have that you're fine, otherwise you can install it separately with npm i -D babel-regenerator-runtime.

Antony Mativos
  • 863
  • 1
  • 8
  • 5
42

My simple solution:

npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator

.babelrc

{
  "presets": [
    ["latest", {
      "es2015": {
        "loose": true
      }
    }],
    "react",
    "stage-0"
  ],
  "plugins": [
    "transform-runtime",
    "transform-async-to-generator"
  ]
}
radzak
  • 2,986
  • 1
  • 18
  • 27
E. Fortes
  • 1,338
  • 12
  • 12
42

This error is caused when async/await functions are used without the proper Babel plugins. As of March 2020, the following should be all you need to do. (@babel/polyfill and a lot of the accepted solutions have been deprecated in Babel. Read more in the Babel docs.)

In the command line, type:

npm install --save-dev @babel/plugin-transform-runtime

In your babel.config.js file, add this plugin @babel/plugin-transform-runtime. Note: The below example includes the other presets and plugins I have for a small React/Node/Express project I worked on recently:

module.exports = {
  presets: ['@babel/preset-react', '@babel/preset-env'],
  plugins: ['@babel/plugin-proposal-class-properties', 
  '@babel/plugin-transform-runtime'],
};
Cat Perry
  • 944
  • 1
  • 11
  • 15
  • What always amazes me is how developers are lazy. Babel devs decided to deprecate functionality, they may expect this to become an issue. Why not to let people know what was the most likely intention, and what should they do to fix it. But no, let's just show some message wich is absoultely useless for newbies. – Pavel Voronin Apr 14 '20 at 16:18
  • 6
    Worked great for me. My non-react project `.babelrc` looks like this: ``` { "presets": [ "@babel/preset-env" ], "plugins": [ "@babel/plugin-transform-runtime" ] } ``` – Anthony May 05 '20 at 22:29
  • I get an error that the property presets is invalid – viv Jun 22 '20 at 07:33
  • 1
    It tells me `Uncaught ReferenceError: require is not defined` – Thielicious Jul 02 '20 at 23:04
  • Thank you! Finally an answer the doesn't use the deprecated @babel/polyfill. This worked for me when trying to use async/await in my tests. – CodeConnoisseur Feb 17 '22 at 20:52
24

babel-regenerator-runtime is now deprecated, instead one should use regenerator-runtime.

To use the runtime generator with webpack and babel v7:

install regenerator-runtime:

npm i -D regenerator-runtime

And then add within webpack configuration :

entry: [
  'regenerator-runtime/runtime',
  YOUR_APP_ENTRY
]
jony89
  • 5,155
  • 3
  • 30
  • 40
  • This should be the accepted answer, babel-polyfill adds way too much other stuff – Shikyo Jun 09 '18 at 16:43
  • Work perfect for me... Thanks a lot – Leandro William Oct 29 '18 at 14:42
  • 1
    This method always include the runtime though. I believe it defeats the purpose of `@babel/preset-env`'s `useBuiltIns` from dynamically inserting runtime based on your target browsers. – kyw Mar 01 '19 at 05:16
20

Update your .babelrc file according to the following examples, it will work.

If you are using @babel/preset-env package

{
  "presets": [
    [
      "@babel/preset-env", {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}
or if you are using babel-preset-env package

{
  "presets": [
    [
      "env", {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}
Zero
  • 1,142
  • 13
  • 10
  • 4
    would please explain your answer ? what "node": "current" does – lazyCoder Nov 13 '18 at 08:41
  • i'd also like to know what this does and if it is a recommended solution - ie it doesn't jeopardise anything and is "future proof" (as much as anything can be at the moment). `targets` seems to refer to [this](https://babeljs.io/docs/en/babel-preset-env#targets) : `the environments you support/target for your project`, whilst `targets.node` is [this](https://babeljs.io/docs/en/babel-preset-env#targetsnode): `if you want to compile against the current node version, you can specify "node": true or "node": "current", which would be the same as "node": process.versions.node` – user1063287 Nov 13 '18 at 09:59
  • FWIW, i used the second block defined in the answer (and removed `"stage-0"` in the process) and the regenerator error went away. – user1063287 Nov 13 '18 at 10:33
  • 2
    @BunkerBoy For convenience, you can use "node": "current" to only include the necessary polyfills and transforms for the Node.js version that you use to run Babel – Zero Nov 19 '18 at 00:18
  • so for this i don't have to install polyfills ? – lazyCoder Nov 20 '18 at 08:29
  • @BunkerBoy Sure, here are all I installed in DevDependencies `"@babel/cli": "^7.1.2", "@babel/core": "^7.1.2", "@babel/node": "^7.0.0", "@babel/preset-env": "^7.1.0"` – Zero Nov 21 '18 at 15:18
  • If you are compiling a library this is likely to cause failures if the user is using an older version of node. For a library, I believe that `transform-runtime` is the correct way of compiling. – Mutai Mwiti Apr 22 '19 at 17:41
15

As of Oct 2019 this worked for me:

Add this to the preset.

 "presets": [
      "@babel/preset-env"
    ]

Then install regenerator-runtime using npm.

npm i regenerator-runtime

And then in your main file use: (this import is used only once)

import "regenerator-runtime/runtime";

This is will enable you to use async awaits in your file and remove the regenerator error

Deke
  • 4,451
  • 4
  • 44
  • 65
  • Not setting a value for [`useBuiltIns`](https://babeljs.io/docs/en/babel-preset-env#usebuiltins) will default it to `false`. This won't auto import any polyfills depending on the target environment, which kinda undermines the purpose of `"@babel/preset-env"`. [Here](https://github.com/babel/babel/issues/6830#issuecomment-344626513) is also a related comment by one of the babel developers. – bela53 Jan 02 '20 at 18:03
14

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

import "babel-polyfill"
async function myFunc(){ }

to this

import "babel-polyfill"
var myFunc = async function(){}

to prevent it being hoisted above the polyfill import.

Ally
  • 4,894
  • 8
  • 37
  • 45
13

I had this problem in Chrome. Similar to RienNeVaPlu͢s’s answer, this solved it for me:

npm install --save-dev regenerator-runtime

Then in my code:

import 'regenerator-runtime/runtime';

Happy to avoid the extra 200 kB from babel-polyfill.

Tom Söderlund
  • 4,743
  • 4
  • 45
  • 67
  • this answer is underrated, it is the simplest solution. However installing it in dev dependency will not work, you need to install it in dependency. My use case is deploying to firebase function nodejs 14 – Acid Coder Oct 09 '21 at 19:13
13

I used tip from https://github.com/babel/babel/issues/9849#issuecomment-592668815 and added targets: { esmodules: true,} to my babel.config.js.

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          esmodules: true,
        },
      },
    ],
  ],
}
k1eran
  • 4,492
  • 8
  • 50
  • 73
  • Why does this solve the problem? – jjmerelo Apr 19 '22 at 11:14
  • 1
    @jjmerelo I only know what I’ve read at the linked GitHub issue. Before this change I tried lots of other answers in this question but in my setup, this was only one that fixed it! – k1eran Apr 19 '22 at 11:19
12

If using babel-preset-stage-2 then just have to start the script with --require babel-polyfill.

In my case this error was thrown by Mocha tests.

Following fixed the issue

mocha \"server/tests/**/*.test.js\" --compilers js:babel-register --require babel-polyfill

Zubair Alam
  • 8,739
  • 3
  • 26
  • 25
10

You'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:

"presets": [
  "es2016",
  // etc...
]

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.

Community
  • 1
  • 1
Galen Long
  • 3,693
  • 1
  • 25
  • 37
10

I started getting this error after converting my project into a typescript project. From what I understand, the problem stems from async/await not being recognized.

For me the error was fixed by adding two things to my setup:

  1. As mentioned above many times, I needed to add babel-polyfill into my webpack entry array:

    ...
    
    entry: ['babel-polyfill', './index.js'],
    
    ...
  2. I needed to update my .babelrc to allow the complilation of async/await into generators:

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

DevDependencies:

I had to install a few things into my devDependencies in my package.json file as well. Namely, I was missing the babel-plugin-transform-async-to-generator, babel-polyfill and the babel-preset-es2015:

 "devDependencies": {
    "babel-loader": "^6.2.2",
    "babel-plugin-transform-async-to-generator": "^6.5.0",
    "babel-polyfill": "^6.5.0",
    "babel-preset-es2015": "^6.5.0",
    "webpack": "^1.12.13"
 }

Full Code Gist:

I got the code from a really helpful and concise GitHub gist you can find here.

Joshua Dyck
  • 2,113
  • 20
  • 25
9

I fixed this error by installing babel-polyfill

npm install babel-polyfill --save

then I imported it in my app entry point

import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';

for testing I included --require babel-polyfill in my test script

"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers 
  js:babel-core/register --require babel-polyfill server/test/**.js --exit"
Ayobami
  • 146
  • 3
  • 4
8

There are so many answers up there, I will post my answer for my reference. I use webpack and react, here is my solution without the .babelrc file

I am working on this in Aug 2020

Install react and babel

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react react react-dom @babel/plugin-transform-runtime --save-dev

Then in my webpack.config.js

// other stuff
module.exports = {
// other stuff

   module: {
   rules: [
  
   {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env',"@babel/preset-react"],
        plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime'],
        //npm install --save-dev @babel/plugin-transform-runtime
          }
        }
      },
    ],
  },

};

I just don't know why I dont need to install the async package for the moment

6

New Answer Why you follow my answer ?

Ans: Because I am going to give you a answer with latest Update version npm project .

04/14/2017

"name": "es6",
 "version": "1.0.0",
   "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "webpack": "^2.3.3",
    "webpack-dev-server": "^2.4.2"

If your Use this version or more UP version of Npm and all other ... SO just need to change :

webpack.config.js

module.exports = {
  entry: ["babel-polyfill", "./app/js"]
};

After change webpack.config.js files Just add this line to top of your code .

import "babel-polyfill";

Now check everything is ok. Reference LINK

Also Thanks @BrunoLM for his nice Answer.

MD Ashik
  • 9,117
  • 10
  • 52
  • 59
  • 1
    Why would he use webpack if it's a backend service? Your answer implies that he has to use webpack? – Spock Oct 06 '17 at 12:38
  • 1
    @Spock, I did think about it. I was facing same Problem and I solved my problem this simple way. I think it's Positive answer for Webpack user and hare have more Right Answer so you can follow anyother . – MD Ashik Oct 06 '17 at 22:37
  • Why you thing you need to press down Vote !!!! Can u say reason if u want to help me. – MD Ashik Aug 31 '18 at 19:01
6

The targeted browsers I need to support already support async/await, but when writing mocha tests, without the proper setting I still got this error.

Most of the articles I googled are outdated, including the accepted answer and high voted answers here, i.e. you don't need polyfill, babel-regenerator-runtime, babel-plugin-transform-runtime. etc. if your target browser(s) already supports async/await (of course if not you need polyfill)

I don't want to use webpack either.

Tyler Long's answer is actually on the right track since he suggested babel-preset-env (but I omitted it first as he mentioned polifill at the beginning). I still got the ReferenceError: regeneratorRuntime is not defined at the first then I realized it was because I didn't set the target. After setting the target for node I fix the regeneratorRuntime error:

  "scripts": {
    //"test": "mocha --compilers js:babel-core/register"
    //https://github.com/mochajs/mocha/wiki/compilers-deprecation
    "test": "mocha --require babel-core/register"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0",
    "mocha": "^5.2.0"
  },
  //better to set it .bablerc, I list it here for brevity and it works too.
  "babel": {
    "presets": [
      ["env",{
        "targets": {
          "node": "current"
           "chrome": 66,
           "firefox": 60,
        },
        "debug":true
      }]
    ]
  }
Qiulang
  • 10,295
  • 11
  • 80
  • 129
6

My working babel 7 boilerplate for react with regenerator runtime:

.babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": true,
        },
      },
    ],
    "@babel/preset-react",
  ],
  "plugins": [
    "@babel/plugin-syntax-class-properties",
    "@babel/plugin-proposal-class-properties"
  ]
}

package.json

...

"devDependencies": {
  "@babel/core": "^7.0.0-0",
  "@babel/plugin-proposal-class-properties": "^7.4.4",
  "@babel/plugin-syntax-class-properties": "^7.2.0",
  "@babel/polyfill": "^7.4.4",
  "@babel/preset-env": "^7.4.5",
  "@babel/preset-react": "^7.0.0",
  "babel-eslint": "^10.0.1",
...

main.js

import "@babel/polyfill";

....
gazdagergo
  • 6,187
  • 1
  • 31
  • 45
6

Easiest way to fix this 'regeneratorRuntime not defined issue' in your console:

You don't have to install any unnecessary plugins. Just add:

<script src="https://unpkg.com/regenerator-runtime@0.13.1/runtime.js"></script>

inside of the body in your index.html. Now regeneratorRuntime should be defined once you run babel and now your async/await functions should be compiled successfully into ES2015

Jackie Santana
  • 1,290
  • 14
  • 15
6

Just install regenerator-runtime with below command

npm i regenerator-runtime

add below line in startup file before you require server file

require("regenerator-runtime/runtime");

So far this has been working for me

Dilip Tarkhala
  • 194
  • 1
  • 4
5

I had a setup
with webpack using presets: ['es2015', 'stage-0']
and mocha that was running tests compiled by webpack.

To make my async/await in tests work all I had to do is use mocha with the --require babel-polyfill option:

mocha --require babel-polyfill
Evgenia Karunus
  • 10,715
  • 5
  • 56
  • 70
5

I get this error using gulp with rollup when I tried to use ES6 generators:

gulp.task('scripts', () => {
  return rollup({
    entry: './app/scripts/main.js',
    format: "iife",
    sourceMap: true,
    plugins: [babel({
      exclude: 'node_modules/**',
      "presets": [
        [
          "es2015-rollup"
        ]
      ],
      "plugins": [
        "external-helpers"
      ]
    }),
    includePaths({
      include: {},
      paths: ['./app/scripts'],
      external: [],
      extensions: ['.js']
    })]
  })

  .pipe(source('app.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({
    loadMaps: true
  }))
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('.tmp/scripts'))
  .pipe(reload({ stream: true }));
});

I may case the solution was to include babel-polyfill as bower component:

bower install babel-polyfill --save

and add it as dependency in index.html:

<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
csharpfolk
  • 4,124
  • 25
  • 31
  • Thank you. This worked for me. I didn't know that I needed to add the script tag for it to work in the client side. – Raza Dec 08 '16 at 21:04
5

1 - Install babel-plugin-transform-async-to-module-method, babel-polyfil, bluebird , babel-preset-es2015, babel-core :

npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core

2 - Add in your js babel polyfill:

import 'babel-polyfill';

3 - Add plugin in your .babelrc:

{
    "presets": ["es2015"],
    "plugins": [
      ["transform-async-to-module-method", {
        "module": "bluebird",
        "method": "coroutine"
      }]
    ]
}

Source : http://babeljs.io/docs/plugins/transform-async-to-module-method/

Luisangonzalez
  • 129
  • 1
  • 7
5

For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.

Npm install the module npm i -D @babel/polyfill

Then in your webpack file in your entry point do this

entry: ['@babel/polyfill', path.resolve(APP_DIR, 'App.js')],
Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
5

To babel7 users and ParcelJS >= 1.10.0 users

npm i @babel/runtime-corejs2
npm i --save-dev @babel/plugin-transform-runtime @babel/core

.babelrc

{
  "plugins": [
    ["@babel/plugin-transform-runtime", {
      "corejs": 2
    }]
  ]
}

taken from https://github.com/parcel-bundler/parcel/issues/1762

Petros Kyriakou
  • 5,214
  • 4
  • 43
  • 82
4

I am using a React and Django project and got it to work by using regenerator-runtime. You should do this because @babel/polyfill will increase your app's size more and is also deprecated. I also followed this tutorial's episode 1 & 2 to create my project's structure.

*package.json*

...
"devDependencies": {
    "regenerator-runtime": "^0.13.3",
    ...
}

.babelrc

{
   "presets": ["@babel/preset-env", "@babel/preset-react"],
   "plugins": ["transform-class-properties"]
}

index.js

...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...
Aaron Miller
  • 185
  • 11
4

for future reference :

As of Babel version 7.0.0-beta.55 stage presets have been removed

refer blog https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets

async await can be still be used by

https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator#usage

installation

npm install --save-dev @babel/plugin-transform-async-to-generator

usage in .babelrc

 { 
     "presets": ["@babel/preset-env"],
     "plugins": ["@babel/plugin-transform-async-to-generator"]
 }

and using babel polyfill https://babeljs.io/docs/en/babel-polyfill

installation

npm install --save @babel/polyfill

webpack.config.js

module.exports = {
  entry: ["@babel/polyfill", "./app/js"],
};
Sharath Mohan
  • 118
  • 1
  • 3
4

If you are using next js, add import regeneratorRuntime from "regenerator-runtime"; to the file that is raising the error, for me, the file was _document.js.

and add

[
  "@babel/plugin-transform-regenerator",
  {
    "asyncGenerators": false,
    "generators": false,
    "async": false
  }
]

in plugins, inside .babelrc file.

Mahdy H.
  • 181
  • 9
3

This solution is out of date.

I found the solution in the youtube comments of this video https://www.youtube.com/watch?v=iWUR04B42Hc&lc=Ugyq8UJq-OyOzsKIIrB4AaABAg

This should direct to the correct comment. Much props to "beth w" for finding the solution.

Beth W 3 months ago (edited)
Another change I had to make in 2019 - babel no longer uses the stage-0 preset as of v7 apparently, so at 26:15 instead of 'npm install --save-dev babel-polyfill babel-preset-stage-0', I had to do:

npm install --save @babel/polyfill

Which covers both of the older options. Then, in the entry point for the app I > included '@babel/polyfill', and in the query presets I left it as-is. So the webpack config ends up looking like:

const path = require('path');
module.exports = {
    entry: {
        app: ['@babel/polyfill', './src/app.js']
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'app.bundle.js'
    },
    mode: 'development',
    module: {
        rules: [{
            test: /\.js?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['@babel/preset-env']
            }
        }]
    }
}

Hope that helps someone!

ShatrdWing
  • 509
  • 4
  • 11
3

try to add this to your package.json

"browserslist": [
  "last 2 Chrome versions"
]

that worked for me!

ybahtiar
  • 31
  • 3
2

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

Petros Kyriakou
  • 5,214
  • 4
  • 43
  • 82
  • I don't see why the downvote and comment. I wanted it for firefox browser. Also i took the info directly from babel website itself. The comment did not help me solve the issue when i tried it. – Petros Kyriakou Dec 30 '17 at 14:15
2

Most of these answers recommend solutions for dealing with this error using WebPack. But in case anyone is using RollUp (like I am), here is what finally worked for me (just a heads-up and bundling this polyfill ads about 10k tot he output size):

.babelrc

{
    "presets": [
        [
            "env",
            {
                "modules": false,
                "targets": {
                    "browsers": ["last 2 versions"]
                }
            }
        ]
    ],
    "plugins": ["external-helpers",
        [
            "transform-runtime",
            {
                "polyfill": false,
                "regenerator": true
            }
        ]]
}

rollup.config.js

import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
import commonjs from 'rollup-plugin-commonjs';


export default {
    input: 'src/entry.js',
    output: {
        file: 'dist/bundle.js',
        format: 'umd',
        name: 'MyCoolLib',
        exports: 'named'
    },
    sourcemap: true,
    plugins: [
        commonjs({
            // polyfill async/await
            'node_modules/babel-runtime/helpers/asyncToGenerator.js': ['default']
        }),
        resolve(),
        babel({
            runtimeHelpers: true,
            exclude: 'node_modules/**', // only transpile our source code
        }),
        uglify()

    ]
};
Maurice
  • 1,223
  • 14
  • 21
  • also for the record... I'm using this config for a plugin I'm building, not a full-blown application. otherwise using `babel-polyfill` would be the recommended solution. – Maurice Dec 24 '17 at 06:58
  • The key is to enable regenerator for babel transform runtime, and that answer already is here below. – Малъ Скрылевъ Dec 29 '17 at 15:46
  • @МалъСкрылевъ Thx for the downvote... and for a suggestion that doesn't actually work. Enabling regenerator alone does NOT work when using RollUp. you need to specify the polyfill in your RollUp config. – Maurice Dec 30 '17 at 06:48
2

If you are building an app, you just need the @babel/preset-env and @babel/polyfill:

npm i -D @babel/preset-env
npm i @babel/polyfill

(Note: you don't need to install the core-js and regenerator-runtime packages because they both will have been installed by the @babel/polyfill)

Then in .babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry"  // this is the key. use 'usage' for further codesize reduction, but it's still 'experimental'
      }
    ]
  ]
}

Now set your target environments. Here, we do it in the .browserslistrc file:

# Browsers that we support

>0.2%
not dead
not ie <= 11
not op_mini all

Finally, if you went with useBuiltIns: "entry", put import @babel/polyfill at the top of your entry file. Otherwise, you are done.

Using this method will selectively import those polyfills and the 'regenerator-runtime' file(fixing your regeneratorRuntime is not defined issue here) ONLY if they are needed by any of your target environments/browsers.

kyw
  • 6,685
  • 8
  • 47
  • 59
2

In 2019 with Babel 7.4.0+, babel-polyfill package has been deprecated in favor of directly including core-js/stable (core-js@3+, to polyfill ECMAScript features) and regenerator-runtime/runtime (needed to use transpiled generator functions):

import "core-js/stable";
import "regenerator-runtime/runtime";

Information from babel-polyfill documentation.

nickbullock
  • 6,424
  • 9
  • 27
2

Just install:

npm install --save-dev @babel/plugin-transform-runtime

and add it to the plugins array of Babel.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
Hilal Aissani
  • 709
  • 8
  • 3
2
  1. Install @babel-polyfill and save it in your dev dependencies

npm install --save-dev @babel/polyfill
  1. Copy and Paste require("@babel/polyfill"); at the top your entry file

Entry.js

require("@babel/polyfill"); // this should be include at the top
  1. Add @babel/polyfill in the entry array

  2. You need preset-env in your preset array

webpack.config.js

const path =  require('path');
require("@babel/polyfill"); // necesarry

module.exports = {
  entry: ['@babel/polyfill','./src/js/index.js'],
  output: {
    path: path.resolve(__dirname, 'to_be_deployed/js'),
    filename: 'main.js'
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },

  mode: 'development'
}
1

I have async await working with webpack/babel build:

"devDependencies": {
    "babel-preset-stage-3": "^6.11.0"
}

.babelrc:

"presets": ["es2015", "stage-3"]
1
  1. Install babel-polyfill npm install --save @babel/polyfill

  2. Update webpack file entry: ["@babel/polyfill", "<your enter js file>"]

Dmitry
  • 183
  • 1
  • 2
  • 8
1

import 'babel-polyfill'

where you using async await

subhajit das
  • 383
  • 3
  • 8
0

In a scenario where a custom babelHelpers.js file is created using babel.buildExternalHelpers() with babel-plugin-external-helpsers I figured the least costly solution for the client is to prepend the regenerator-runtime/runtime.js to the output instead of all polyfills.

// runtime.js
npm install --save regenerator-runtime

// building the custom babelHelper.js
fs.writeFile(
    './babelHelpers.js',
    fs.readFileSync('node_modules/regenerator-runtime/runtime.js')
    + '\n'
    + require('babel-core').buildExternalHelpers()
)

This solution comes down to about 20 KB instead of ~230 KB when including babel-polyfill.

RienNeVaPlu͢s
  • 7,442
  • 6
  • 43
  • 77
0

i had regeneratorRuntime is not defined error when i used 'async' and 'await' in my react app 'async' and 'await' is a new keywords in ES7 for that you should use babel-preset-es2017 install this devDependencies:

`

"babel-preset-es2017": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1", `

and use this

"presets": [ "es2017" , "stage-0" , "react" ]

Anas Alpure
  • 510
  • 5
  • 9
0

I was encountering this issue when trying to run Mocha + Babel. I had a .babelrc that worked in development (see the other answers here, they are pretty complete), but my npm run test command was still complaining about regeneratorRuntime is not defined. So I modified my package.json:

"scripts": {
  "test": "mocha --require babel-polyfill --require babel-core/register tests/*.js"
}

Read more: https://babeljs.io/en/setup/#mocha-4

helsont
  • 4,347
  • 4
  • 23
  • 28
0

Using stage-2 preset before react preset helped me:

npx babel --watch src --out-dir . --presets stage-2,react

The above code works when the following modules are installed:

npm install babel-cli babel-core babel-preset-react babel-preset-stage-2 --save-dev
Charles
  • 227
  • 1
  • 5
0

Alternatively, if you are not using a bundler like webpack or rollup, you could as a workaround just import the contents of https://raw.githubusercontent.com/facebook/regenerator/master/packages/regenerator-runtime/runtime.js using a plain old script tag in your index.html.

Not optimal, but in my case the only solution.

fmi21
  • 485
  • 3
  • 15