Error referenceerror regeneratorruntime is not defined

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" ] } pac...

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's user avatar

Lemmings19

1,2832 gold badges24 silver badges34 bronze badges

answered Nov 4, 2015 at 17:10

BrunoLM's user avatar

BrunoLMBrunoLM

96.4k82 gold badges297 silver badges449 bronze badges

23

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's user avatar

answered Apr 24, 2016 at 10:34

johnny's user avatar

johnnyjohnny

5,0171 gold badge16 silver badges9 bronze badges

14

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

answered Dec 12, 2018 at 4:27

Matt Shirley's user avatar

Matt ShirleyMatt Shirley

4,1871 gold badge15 silver badges19 bronze badges

10

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.

answered Dec 26, 2016 at 12:27

Tyler Liu's user avatar

Tyler LiuTyler Liu

18.9k11 gold badges98 silver badges83 bronze badges

13

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).

answered Jun 25, 2019 at 12:35

ford04's user avatar

ford04ford04

60.7k16 gold badges184 silver badges166 bronze badges

4

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.

answered Apr 13, 2016 at 7:01

Antony Mativos's user avatar

Antony MativosAntony Mativos

8431 gold badge8 silver badges5 bronze badges

2

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's user avatar

radzak

2,8461 gold badge17 silver badges26 bronze badges

answered Jun 19, 2017 at 15:09

E. Fortes's user avatar

E. FortesE. Fortes

1,33112 silver badges11 bronze badges

5

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'],
};

answered Apr 14, 2020 at 15:08

Cat Perry's user avatar

Cat PerryCat Perry

8841 gold badge11 silver badges14 bronze badges

5

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
]

answered Jan 3, 2018 at 13:53

jony89's user avatar

jony89jony89

4,9473 gold badges30 silver badges40 bronze badges

3

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

answered Oct 26, 2018 at 14:15

Zero's user avatar

ZeroZero

1,11213 silver badges10 bronze badges

7

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

answered Oct 14, 2019 at 21:24

Deke's user avatar

DekeDeke

4,3124 gold badges42 silver badges62 bronze badges

1

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.

answered Apr 23, 2018 at 4:33

Ally's user avatar

AllyAlly

4,7968 gold badges36 silver badges45 bronze badges

1

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

answered Aug 19, 2016 at 9:48

Zubair Alam's user avatar

Zubair AlamZubair Alam

8,5533 gold badges25 silver badges25 bronze badges

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.

answered Aug 2, 2018 at 9:27

Tom Söderlund's user avatar

Tom SöderlundTom Söderlund

4,6134 gold badges43 silver badges62 bronze badges

1

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's user avatar

answered Feb 27, 2017 at 20:54

Galen Long's user avatar

Galen LongGalen Long

3,5831 gold badge24 silver badges36 bronze badges

0

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.

answered Jan 31, 2018 at 5:21

Joshua Dyck's user avatar

Joshua DyckJoshua Dyck

2,03519 silver badges25 bronze badges

1

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"

answered Dec 12, 2017 at 13:41

Ayobami's user avatar

AyobamiAyobami

1463 silver badges4 bronze badges

0

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

answered Aug 25, 2020 at 6:19

The gates of Zion's user avatar

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.

answered Apr 14, 2017 at 5:50

MD Ashik's user avatar

MD AshikMD Ashik

8,5067 gold badges51 silver badges56 bronze badges

3

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

answered Jul 31, 2018 at 5:20

Qiulang's user avatar

QiulangQiulang

9,2619 gold badges74 silver badges116 bronze badges

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

....

answered Jun 21, 2019 at 13:55

gazdagergo's user avatar

gazdagergogazdagergo

5,6781 gold badge29 silver badges44 bronze badges

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

answered Mar 23, 2020 at 23:36

Jackie Santana's user avatar

1

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

answered Nov 10, 2020 at 13:52

Dilip Tarkhala's user avatar

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>

answered Nov 20, 2016 at 10:13

csharpfolk's user avatar

csharpfolkcsharpfolk

4,07624 silver badges30 bronze badges

1

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/

answered Jan 7, 2017 at 12:10

Luisangonzalez's user avatar

0

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')],

answered Jan 17, 2018 at 11:14

Adeel Imran's user avatar

Adeel ImranAdeel Imran

12.4k7 gold badges58 silver badges77 bronze badges

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

answered Oct 19, 2018 at 21:35

Petros Kyriakou's user avatar

Petros KyriakouPetros Kyriakou

5,1144 gold badges42 silver badges82 bronze badges

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

answered Sep 7, 2016 at 20:40

Evgenia Karunus's user avatar

Evgenia KarunusEvgenia Karunus

10.5k5 gold badges56 silver badges69 bronze badges

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'));
...

answered Jul 22, 2019 at 18:59

Aaron Miller's user avatar

0

I’m building an SSR template, and when I use @babebl/register and then execute webpack (config), the system reported an error.
I tried @babel/polyfill and @babel/plugin-transform-runtime, but none of them worked.

Input code

index.js:

require("ignore-styles");
require("@babel/register")({
  ignore: [//(build|node_modules)//],
  presets: ["@babel/preset-env", "@babel/preset-react"],
  plugins: ["@babel/plugin-syntax-dynamic-import", "dynamic-import-node"]
});
require("./server");

server.js

const config = require('../config/webpack.dev.config.js')
const webpack = require('webpack')
const express = require('express')
const webpackDevMiddleware = require('webpack-dev-middleware') 
const reactRouter = require('react-router')
const StaticRouter = reactRouter.reactRouter;
const app = express()
const complier = webpack(config)
const PORT = 8090
...
app.use(webpackDevMiddleware(complier, {
  publicPath: config.output.publicPath
}))

app.listen(PORT , function() {
  console.log(`SSR running on port ${PORT }`);
})

webpack.dev.config.js

const paths = require('./paths')
const webpack = require('webpack')
const htmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: ['webpack-hot-middleware/client?reload=true', paths.appIndexJs],
  output: {
    path: paths.clientBuild,
    filename: '[name].bundle.js',
    chunkFilename: '[name].bundle.js',
    publicPath: paths.publicPath
  },
  devtool: 'eval-source-map',
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { 
              useBuiltIns: 'usage', 
              corejs: "2",  
              targets: {
                  browsers: ['last 2 versions', 'ie >= 9'],
              },
            }],
            '@babel/preset-react'
          ]
        }
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new htmlWebpackPlugin({
      template: './client/index.html',
      filename: 'index.html'
    })
  ]
}

Error message

image

Environment

  • Babel version(s): 7.4.3
  • Node/npm version: [e.g. Node 10.15.3/npm 6.4.1]
  • OS: window 10

Rep

https://github.com/xuchenchenBoy/ssr (Please execute npm run dev:server and release notes in server.js)

Hello Guys, How are you all? Hope You all Are Fine. Today I am facing the Following error in my project Babel ReferenceError: regeneratorRuntime is not defined in Javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

Contents

  1. How Babel ReferenceError: regeneratorRuntime is not defined Error Occurs ?
  2. How To Solve Babel ReferenceError: regeneratorRuntime is not defined Error ?
  3. Solution 1: babel-polyfill is Required
  4. Solution 2: use babel-plugin-transform-runtime inOrder to support async/await
  5. Solution 3: For Babel 7 User
  6. Summery

I am trying t use the async-await function But I am facing the following error.


ReferenceError: regeneratorRuntime is not defined

How To Solve Babel ReferenceError: regeneratorRuntime is not defined Error ?

  1. How To Solve Babel ReferenceError: regeneratorRuntime is not defined Error?

    To Solve Babel 6 ReferenceError: regeneratorRuntime is not defined Error Here babel-polyfill is Required You have to install babel-polyfill to get async/await working. Install babel-polyfill by this command. npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader

  2. Babel ReferenceError: regeneratorRuntime is not defined

    To Solve Babel 6 ReferenceError: regeneratorRuntime is not defined Error Here babel-polyfill is Required You have to install babel-polyfill to get async/await working. Install babel-polyfill by this command. npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader

Solution 1: babel-polyfill is Required

Here babel-polyfill is Required You have to install babel-polyfill to get async/await working. Install babel-polyfill by this command.

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

Here is your 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"
}

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

Now you can use async await like this. Here is my example.

"use strict";

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

function bar() {
  return "bar";
}

Solution 2: use babel-plugin-transform-runtime inOrder to support async/await

Here use babel-plugin-transform-runtime inOrder to support async/await 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
    }]
  ]
}

Solution 3: For Babel 7 User

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also, Read

  • SyntaxError: invalid syntax to repo init in the AOSP code.

11 November 2018

I was tinkering with my antiquated, silly, and super tiny NPM module this morning: giphy-random. It basically for retrieving a random GIF using the Gihpy API.

I simplified the code, from the class-based to just a simple function. I also replaced the Promise syntax with the async-await style. It’s super simple:

import axios from "axios";

const giphyRandom = async (apiKey, { tag, rating = "g" } = {}) => {
  const params = { api_key: apiKey, rating };

  if (tag) {
    params.tag = tag;
  }

  const { data } = await axios.get("https://api.giphy.com/v1/gifs/random", {
    params
  });

  return data;
};

export default giphyRandom;

Then I went ahead and upgraded the babel package to the latest version 7. Using Babel 7 means I no longer need to use the babel-plugin-external-helpers. This plugin was used to prevent Babel from injecting the same helper functions on each file its transformed.

My .babelrc looks simpler without any additional plugins:

{
  "presets": [
    ["@babel/env", {
      "modules": false
    }]
  ]
}

The modules is set to false because I use rollup to bundle my library—which can handle the ES module.

The Error

When I build this tiny library, an error arises from the UMD build:

giphy-random.umd.js:59 Uncaught ReferenceError: regeneratorRuntime is not defined
    at giphy-random.umd.js:59
    at giphy-random.umd.js:104
    at giphy-random.umd.js:4
    at giphy-random.umd.js:5

If you’ve been working with Babel, you might’ve already known the culprit. This error usually shows up when you use the generator or async function in your code.

The Culprit

When you support some older browsers that can’t handle the generator or async syntax. Babel will transform your generator/async code into a backward-compatible ES5 syntax.

Here’s my .browserslistrc file. And apparently, some browsers in that query still does not support async function 😅.

last 1 version
>= 5%
not dead

Here’s the snippet of generated UMD build from my giphy-random library:

var giphyRandom =
/*#__PURE__*/
function () {
  var _ref = _asyncToGenerator(
  /*#__PURE__*/
  regeneratorRuntime.mark(function _callee(apiKey) {
    // Omitted...

    return regeneratorRuntime.wrap(function _callee$(_context) {
      // Omitted...
    }, _callee, this);
  }));

  return function giphyRandom(_x) {
    return _ref.apply(this, arguments);
  };
}();

The Solutions

As you can see the async giphyRandom function is transformed. And the error is thrown because it can’t find the reference to the regeneratorRuntime. There are two possible solutions here:

  1. Let the user provides this regeneratorRuntime module itself.
  2. Include this regeneratorRuntime module in our bundle.

The first approach is just too much of a hassle for the user. So let’s include this regeneratorRuntime module in our bundle. (Or you can just drop the support for older browsers 😉)

There are also three ways of including this regeneratorRuntime module in your bundle:

  1. Import the module explicitly: regenerator-runtime.
  2. Use the Babel plugin: @babel/plugin-transform-runtime.
  3. Or if you use @babel/preset-env, you can simply set the useBuiltIns option to usage.

The first solution is not scalable. Imagine that in the future all the browsers in our .browserslistrc file finally support this async function. But because we explicitly import the regenerator-runtime, this module will always be included in our final bundle.

With the second and the third approach, the regeneratorRuntime module will only be injected if the targetted environment does not support a generator or async function.

To execute the second solution, first install the plugin:

$ npm install @babel/plugin-transform-runtime -D

# If you use Yarn
$ yarn add @babel/plugin-transform-runtime -D

Next, register this plugin on your .babelrc file:

{
  "presets": [
    ["@babel/env", {
      "modules": false
    }]
  ],
  "plugins": ["@babel/plugin-transform-runtime"]
}

Finally, update the babel plugin parameter on your Rollup configuration file. Set the runtimeHelpers argument to true.

Here’s the snippet of giphy-random’s Rollup configuration for the UMD build format:

import babel from "rollup-plugin-babel";
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";

import pkg from "./package.json";

export default [
  {
    input: "src/index.js",
    output: {
      file: pkg.browser,
      format: "umd",
      name: "giphyRandom",
      globals: {
        axios: "axios"
      }
    },
    external: ["axios"],
    plugins: [
      resolve(),
      commonjs(),
      babel({
        exclude: "node_modules/**",
        runtimeHelpers: true
      })
    ]
  }
];

The third solution is a lot more simpler. All we have to do is set the useBuiltIns option to usage on our .babelrc file:

{
  "presets": [
    ["@babel/env", {
      "modules": false,
      "useBuiltIns": "usage"
    }]
  ]
}

Babel will automatically import the polyfills for the features that we only use. The polyfill itself is provided by the core-js.

Now everything should be working fine 👌🏻

Понравилась статья? Поделить с друзьями:
  • Error referenceerror localstorage is not defined
  • Error remote origin already exists перевод
  • Error reference source not found как исправить
  • Error reference number 525
  • Error reference number 524