Javascript 未定义 RegeneratorRuntime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28976748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:41:10  来源:igfitidea点击:

RegeneratorRuntime is not defined

javascriptkarma-runnerbabeljskarma-babel-preprocessor

提问by P.Brian.Mackey

I am trying to run Karma-babel-preprocessorand a straight forward ES6 generator:

我正在尝试运行Karma-babel-preprocessor和一个直接的 ES6 生成器:

//require('babel/polyfill');

  describe("how Generators work", function() {
    it("will allow generator functions", function() {
      /*function * numbers() {
        yield 1;
        yield 2;
        yield 3;
      };*/


      let numbers = {
        [Symbol.iterator]:function*(){
            yield 1;
            yield 2;
            yield 3;
          }
      }

      let sum = 0;

      for(n of numbers){
        sum += n;
      }

      expect(sum).toBe(6);
    });
  });

From this I generated my test files (ES6 => ES5) with babel:

由此我用 babel 生成了我的测试文件(ES6 => ES5):

babel src --watch --out-dir tests

babel src --watch --out-dir tests

Then I run karma startI get error:

然后我运行karma start我得到错误:

ReferenceError: regeneratorRuntime is not defined".

参考错误:未定义 regeneratorRuntime”。

Relevant bits in karma.conf.js:

karma.conf.js 中的相关位:

  // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      {pattern: 'tests/*.js', included: true}
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
            'src/*.js': ['babel']
    },
        'babelPreprocessor': {
      options: {
        sourceMap: 'inline'
      },
      filename: function(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function(file) {
        return file.originalPath;
      }
    },


// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],

Full project on github

github上的完整项目

I am able to use many ES6 features including arrows. Just no go on Generators.

我能够使用许多 ES6 特性,包括箭头。只是不去发电机。

采纳答案by Martin

While I'm taking a different approach** to using Karma with Babel in my project, I suspect you're having the same problem I was: the Babel polyfillis not being loaded, and so you're not getting the functionality it supports (including the custom regenerator runtime that Babel uses to make generators work).

虽然我采用不同的方法**在我的项目中使用 Karma 和 Babel,但我怀疑您遇到了与我相同的问题:未加载Babel polyfill,因此您没有获得它支持的功能(包括 Babel 用来使生成器工作的自定义再生器运行时)。

One approach would be to find a way to include the polyfill, perhaps by feeding it to Karma via the files array:

一种方法是找到一种包含 polyfill 的方法,也许是通过 files 数组将其提供给 Karma:

files: [
  'path/to/browser-polyfill.js', // edited: polyfill => browser-polyfill per P.Brian.Mackey's answer
  ...

An alternate approach may be to use Babel's runtime transformer[edit: on rereading the docs, this will not work unless you then browserify/webpack/etc. to process the require()calls created by the transformer]; per its docs,

另一种方法可能是使用 Babel 的运行时转换器[编辑:在重新阅读文档时,除非你浏览器/webpack/等,否则这将不起作用。处理require()由转换器创建的调用]; 根据其文档,

The runtimeoptional transformer does three things:

  • Automatically requires babel-runtime/regeneratorwhen you use generators/async functions.
  • Automatically requires babel-runtime/core-jsand maps ES6 static methods and built-ins.
  • Removes the inline babel helpers and uses the module babel-runtime/helpersinstead.

runtime可选的变压器做了三两件事:

  • babel-runtime/regenerator当您使用生成器/异步函数时自动需要。
  • 自动需要babel-runtime/core-js和映射 ES6 静态方法和内置函数。
  • 删除内联 babel 助手并使用module babel-runtime/helpers代替。

I have no experience with this, but I suspect you would do so by including the optional: ['runtime']option from the Babel docs in your babelPreprocessorconfig, viz.:

我没有这方面的经验,但我怀疑您会通过optional: ['runtime']babelPreprocessor配置中包含Babel 文档中的选项来实现,即:

'babelPreprocessor': {
  options: {
    optional: ['runtime'],  // per http://babeljs.io/docs/usage/options/
    sourceMap: 'inline'
  },
...

(** I'm currently using jspm + jspm-karma + some config to get the Babel polyfill to load in SystemJS; ask if relevant and I'll expound.)

** 我目前正在使用 jspm + jspm-karma + 一些配置来让 Babel polyfill 加载到 SystemJS 中;询问是否相关,我会详细说明。

回答by arcseldon

Node js Env - updated December 2015

Node js Env - 2015 年 12 月更新

This question has already been answered, please see accepted answer UNLESS running within NodeJS environment.

此问题已得到解答,请参阅已接受的答案,除非在 NodeJS 环境中运行。

If like myself, you had the same error message: 'ReferenceError: regeneratorRuntime is not defined'but were running Babel within a NodeJS environment, then simply doing the following will likely solve your problem:

如果像我一样,你有同样的错误信息:'ReferenceError: regeneratorRuntime is not defined'但是在 NodeJS 环境中运行 Babel,那么简单地执行以下操作可能会解决你的问题:

npm install babel-polyfill --save

Then insert the following require statement towards the top of the affected module to obtain required (generator) behaviour:

然后在受影响模块的顶部插入以下 require 语句以获得所需的(生成器)行为:

require("babel-polyfill");

This should be all you need, just importing the module adds required polyfill behaviour at runtime.

这应该就是您所需要的,只需导入模块即可在运行时添加所需的 polyfill 行为。

回答by Kevin

Similar to the post by arcseldon, I was running Babel within a NodeJS environment and getting the same error message 'ReferenceError: regeneratorRuntime is not defined'. While installing babel-polyfill does work, I went with @babel/plugin-transform-runtime instead.

与 arcseldon 的帖子类似,我在 NodeJS 环境中运行 Babel 并收到相同的错误消息“ReferenceError: regeneratorRuntime is not defined”。虽然安装 babel-polyfill 确实有效,但我改为使用 @babel/plugin-transform-runtime。

@babel/plugin-transform-runtime

@babel/plugin-transform-runtime

It needs to be installed in two ways ... first as a dev dependency:

它需要以两种方式安装......首先作为开发依赖项:

npm install --save-dev @babel/plugin-transform-runtime

and second as a production dependency:

其次是生产依赖:

npm install --save @babel/runtime

And then there needs to be one simple addition to your .babelrc file:

然后需要在 .babelrc 文件中添加一个简单的内容:

{
  "plugins": ["@babel/plugin-transform-runtime"]
}

These additions give ES6 authoring functionality without the ReferenceError.

这些添加为 ES6 创作功能提供了没有 ReferenceError 的功能。

回答by P.Brian.Mackey

I modified karma.conf.jsto add browser-polyfillas mentionedin the Docs Link:

我修改karma.conf.js补充browser-polyfill提到文档链接

files: [
            'node_modules/babel/browser-polyfill.js',
      'test-main.js',
      {pattern: 'tests/*.js', included: true}
    ],

After this modification, the following unit test works in Karma:

在此修改后,以下单元测试在 Karma 中工作:

  describe("how Generators work", function() {
    it("will allow generator functions", function() {
     /*function* numbers(){
       yield 1;
       yield 2;
       yield 3;
     };*///Simplified syntax does not work

      let numbers = {
        [Symbol.iterator]:function*(){
            yield 1;
            yield 2;
            yield 3;
          }
      }

      let sum = 0;

      for(let num of numbers){
        sum += num;
      }

      expect(sum).toBe(6);
    });
  });

回答by Rafal Enden

If you use React, adding polyfills from create-react-appworked for me.

如果你使用React,添加 polyfillscreate-react-app对我有用。

yarn add --dev react-app-polyfill

Then add the following lines to webpack.config.js

然后将以下行添加到 webpack.config.js

entry: {
  app: [
    'react-app-polyfill/ie9', // Only if you want to support IE 9
    'react-app-polyfill/stable',
    './src/index.jsx',
  ],
},

See more examples on the react-app-polyfill GitHub page.

react-app-polyfill GitHub 页面上查看更多示例。