Uncaught ReferenceError: regeneratorRuntime is not defined – Two Solutions

Trying to use async/await in my React app gave me this error Uncaught ReferenceError: regeneratorRuntime is not defined. I found two solutions

First, this is the code I was trying to run

require('whatwg-fetch');

const ROOT_API_URL = 'https://api.github.com/';
const ACCESS_TOKEN = 'access_token=9d...c0';

const fetchUser = async () => {
  const url = `${ROOT_API_URL}user?${ACCESS_TOKEN}`;
  const response = await fetch(url);
  const body = await response.json();

  if (response.status !== 200) 
    throw Error(body.message);

  return body;
}

module.exports = {
  fetchUser
}

And the error

Solution 1

Use babel-preset-env. If you are using babel-preset-es2015, just replace it with babel-preset-env and you will get the latest Babel plugins support.

// If you are using ES2015 preset
yarn remove babel-preset-es2015

yarn add -D babel-preset-env

Then add the following Babel configuration via .babelrc

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

[Source]

Solution 2

You will need a polyfill for browser support and have the regeneratorRuntime.

Install the following two packages

yarn add -D babel-plugin-transform-regenerator
yarn add babel-polyfill

Add the following Babel configuration via .babelrc

{
  "plugins": ["transform-regenerator"]
}

In your webpack configuration add

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

Note: babel-polyfill needs to be before your main app JavaScript entry.

And finally import the polyfill in your top-most container

...
import 'babel-polyfill';
...

Now async/await should be working.

[Source]
babel-plugin-transform-regenerator
babel-polyfill



 

Esau Silva
Software Engineer at Region One ESC
Full Stack Software Engineer working with Microsoft technologies, ReactJS is awesome and avid Brazilian Jiu-Jitsu practitioner
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed.
Share