Babel 7 - ReferenceError: regeneratorRuntime is not defined
Asked Answered
L

9

107

I have an application that is a node backend and a react frontend.

I get the following error when i try to build/run my node application.

Node: v10.13.0

Error:

dist/index.js:314 regeneratorRuntime.mark(function _callee(productId) { ^

ReferenceError: regeneratorRuntime is not defined

.babelrc

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

webpack.config.js

{
        mode: "development",
        entry: "./src/index.js",
        target: "node",
        externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
        stats: {
            colors: true
        },
        devtool: "source-map",

        output: {
            path: path.resolve(__dirname, "dist"),
            filename: "index.js",
            sourceMapFilename: "index.js.map"
        },
        module: {
            rules: [
                {
                    enforce: "pre",
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: "eslint-loader",
                },
                {
                    test: /\.m?js$/,
                    exclude: /(node_modules|bower_components)/,
                    use: {
                        loader: "babel-loader",
                        options: {
                            presets: ["@babel/preset-env"]
                        }
                    }
                }
            ],
        },
        node: {
            __dirname: false,
            __filename: false,
        },

        "plugins": [
            new CleanWebpackPlugin(),
            new WebpackShellPlugin({
                onBuildStart: [],
                onBuildEnd: ["nodemon dist/index.js"]
            }),

        ]

    },

package.json

 "dependencies": {
    "connect": "^3.6.6",
    "cors": "^2.8.5",
    "dotenv": "^6.1.0",
    "express": "^4.16.4",
    "hellojs": "^1.17.1",
    "i18n-iso-countries": "^3.7.8",
    "morgan": "^1.9.1",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "request": "^2.88.0",
    "request-promise-native": "^1.0.5",
    "serve-static": "^1.13.2",
    "vhost": "^3.0.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.1.5",
    "@babel/core": "^7.1.6",
    "@babel/plugin-proposal-class-properties": "^7.1.0",
    "@babel/preset-env": "^7.1.6",
    "@babel/preset-react": "^7.0.0",
    "babel-eslint": "^10.0.1",
    "babel-loader": "^8.0.4",
    "clean-webpack-plugin": "^1.0.0",
    "copy-webpack-plugin": "^4.6.0",
    "css-loader": "^1.0.1",
    "eslint": "^5.9.0",
    "eslint-config-google": "^0.10.0",
    "eslint-loader": "^2.1.1",
    "eslint-plugin-react": "^7.11.1",
    "extract-loader": "^3.0.0",
    "file-loader": "^2.0.0",
    "node-sass": "^4.10.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.26.0",
    "webpack-cli": "^3.1.2",
    "webpack-node-externals": "^1.7.2",
    "webpack-shell-plugin": "^0.5.0"
  }
Lian answered 30/11, 2018 at 13:55 Comment(0)
S
200

Updated Answer:

If you are using Babel 7.4.0 or newer, then @babel/polyfill has been deprecated. Instead, you will want to use the following at the top of your main js file (likely index.js or similar):

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

Install these packages either with npm:

npm install --save core-js
npm install --save regenerator-runtime    

or with yarn:

yarn add core-js
yarn add regenerator-runtime

Original Answer:

I just encountered this problem and came across the following solution:

In package.json I had @babel/polyfill as a dependency. However, in my index.js (My main js file) I had neglected to place the following line at the the top:

import '@babel/polyfill'

Once I imported it, everything worked fine.

I did not need to install babel-runtime as other answers are suggesting.

Signification answered 2/2, 2019 at 5:40 Comment(10)
You, my friend, deserve a cookie! I second there's no need to install any runtimeMaighdiln
wow, this is the only up-to-date answer about this on the entire internetBelongings
Would still be interesting to know why at all this runtime is needed. Why can't it transform async functions to simple promises?Yorick
Importing core-js/stable through import "core-js/stable"; generates a very big bundle. Is there a way to tell Babel to only polyfill what it's needed?Snob
Where should I put the import statements?Obsolescent
I just want to add that the import statements must be loaded first in order to work!Purslane
@Snob import 'core-js/features/promise';Escutcheon
@ford04's solution is more in-depth, lists all the possible solutions, and cites sources.Raffinose
Do we still need the regenerator-runtime/runtime?Venator
A working configuration is a moving target with a lot of byzantine bits. "Babel" seems more aptly named every time I update a dependency.Phenica
A
117

Babel 7.4.0 and later

There are two main configurations - one for apps and one for libraries.

Option 1: App

When to use: ✔ for applications ✔ global scope polyfills ✔ smallest bundle size ✔ selective inclusion via targets ✔ No need to process node_modules for polyfills

"presets": [
  [
    "@babel/preset-env",
    {
      "useBuiltIns": "usage", // alternative mode: "entry"
      "corejs": 3, // default would be 2
      "targets": "> 0.25%, not dead" 
      // set your own target environment here (see Browserslist)
    }
  ]
]
Install dependencies:
npm i --save-dev @babel/preset-env

npm i regenerator-runtime core-js // run-time dependencies
// regenerator-runtime: transform (async) generators and `async`/`await`
// core-js: other ECMAScript features like Promise, Set, etc.

@babel/preset-env selectively includes polyfills for targets, specified by a Browserslist query. There are two modes - try usage first (more convenient), else entry (more flexible and robust):

  • useBuiltIns 'usage': no need to import anything manually. All polyfills are added automatically based on their code usage in a file.

  • useBuiltIns 'entry': Add these import entries once (!) in your app - akin to @babel/polyfill:

    import "regenerator-runtime/runtime";
    import "core-js/stable"; // or more selective import, like "core-js/es/array"
    

Extension

For advanced cases, you might use @babel/transform-runtime (dev) and @babel/runtime (run-time) only for Babel helpers to reduce bundle size a bit more - called helper aliasing.

Option 2: Library

When to use: ✔ for libraries ✔ no global scope pollution ✔ includes all polyfills, not selective ✔ bigger bundle size neglectable

"plugins": [
  [
    "@babel/plugin-transform-runtime",
    {
      "regenerator": true,
      "corejs": 3
    }
  ]
]
Install compile-time and run-time dependencies:
npm i --save-dev @babel/plugin-transform-runtime // only for build phase

npm i @babel/runtime // runtime babel helpers + just regenerator runtime
// OR (choose one!)
npm i @babel/runtime-corejs3 
// also contains other JS polyfills (not only regenerator runtime)
// depends on core-js-pure ("ponyfills"/polyfills that don't pollute global scope)

See @babel/plugin-transform-runtime, @babel/runtime, @babel/runtime-corejs.

Extension

You can additionally use @babel/preset-env for syntax transpilation only, with useBuiltIns: false. As the library option does not use global polyfills, you might want to transpile node_modules as well - see the absoluteRuntime option.

Closing notes

Alto answered 30/4, 2020 at 6:54 Comment(0)
I
57

There is already a very good answer here (originally posted on the Babel6 question) which I will just translate to Yarn. Basically, you need babel runtime (NOT as a dev dependency) and the plugin transform-runtime

yarn add @babel/runtime 
yarn add -D @babel/plugin-transform-runtime

And, in .babelrc, add:

{
    "presets": ["@babel/preset-env"],
    "plugins": ["@babel/transform-runtime"]
}
Indole answered 29/12, 2018 at 23:8 Comment(3)
This hint actually saved me. I was trying with DEV dependency and it didn't work. Could you please explain WHY it is working now :)Constitutionality
@babel/runtime is needed as a dependency for your code to run @babel/plugin-transform-runtime is needed when babel compiles your codeCaeoma
Considering the result, is there any difference between your method and the accepted answer?Venator
B
26

I had this error in my react project with webpack 4 and this was preventing the whole project to get rendered.

This is how I solved it:

Install plugin-transform-runtime:

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

Add plugin-transform-runtime to the plugin's list in the .babelrc file:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    ["@babel/transform-runtime"]  // <= Add it here
  ]  
}
Busman answered 1/2, 2020 at 13:7 Comment(0)
R
3

For me worked:

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          esmodules: true,
        },
      },
    ],
  ],
}
Racial answered 13/5, 2022 at 14:19 Comment(2)
I'd love to read more about why this works! (And it did work for me as well.)Lockwood
@AdamEasterling I would like to give you more information but sadly I can't. I searched many hours for a solution and tried a lot of approches but I don't know where I saw this and why this works.Racial
P
0

I just solved this error when I imported babel-polyfill directly into the file that shows the error, for example, the error says "ReferenceError: regeneratorRuntime is not defined at /dist/models/usersSchema.js", so I use this in my usersSchema.js file:

require("babel-polyfill");

(you can use import "babel-polyfill";as well)

Permittivity answered 17/4, 2020 at 1:24 Comment(1)
babel-polyfill is deprecated.Venator
S
0

Make sure you are using @babel/runtime at version 7.18 or greater.

I found the explanation for this error and the solution here: https://github.com/ant-design/pro-components/issues/5273#issuecomment-1133843012

Scarborough answered 25/7, 2023 at 8:44 Comment(0)
F
-1

You will need to have the regeneratorRuntime.

Install this two packages - babel-plugin-transform-regenerator and babel-polyfill

Add the following Babel configuration via .babelrc

{
  "plugins": ["transform-regenerator"]
}
Fallingout answered 30/11, 2018 at 14:5 Comment(3)
I think the other thing to do is to install babel-polyfill and require it at the topmost level of the application- import 'babel-polyfill';Fallingout
Using babel 7 with yarn add -D @babel/polyfill @babel/transform-regenerator and adding "@babel/transform-regenerator" to my babelrc plugins did not workIndole
This solved my issueDisenthral
D
-4

React.js Users

If this issue faced you while using react (specifically while trying to use Async/Wait), then Valentino Gagliardi provided a detailed approach on his blog regarding how to address this issue

Demerol answered 3/10, 2019 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.