Babel 6 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" ] } p...

问题:

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?


回答1:

babel-polyfill 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

回答2:

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", {
      "polyfill": false,
      "regenerator": true
    }]
  ]
}

回答3:

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.


回答4:

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

回答5:

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.


回答6:

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

回答7:

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
]

回答8:

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.


回答9:

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


回答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.


回答11:

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.


回答12:

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

回答13:

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.


回答14:

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"

回答15:

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

回答16:

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


回答17:

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/


回答18:

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.


回答19:

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

回答20:

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 add mocha --require babel-polyfill option.


回答21:

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>

回答22:

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


回答23:

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

    ]
};

回答24:

I have async await working with webpack/babel build:

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

.babelrc:

"presets": ["es2015", "stage-3"]

回答25:

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.


回答26:

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


回答27:

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.

  • 发表于 2019-03-31 20:26
  • 阅读 ( 8578 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除