Babel 6 regeneratorRuntime is not defined

2018-12-31 23:10发布

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?

26条回答
牵手、夕阳
2楼-- · 2019-01-01 00:02

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

查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 00:02

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.

查看更多
低头抚发
4楼-- · 2019-01-01 00:04

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.

查看更多
一个人的天荒地老
5楼-- · 2019-01-01 00:04

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

    ]
};
查看更多
琉璃瓶的回忆
6楼-- · 2019-01-01 00:06

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
]
查看更多
浪荡孟婆
7楼-- · 2019-01-01 00:07

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 entry 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
查看更多
登录 后发表回答