RegeneratorRuntime is not defined
Asked Answered
A

5

42

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

//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 src --watch --out-dir tests

Then I run karma start I get error:

ReferenceError: regeneratorRuntime is not defined".

Relevant bits in 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

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

Acquisition answered 11/3, 2015 at 0:54 Comment(0)
A
27

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

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

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,

The runtime optional transformer does three things:

  • Automatically requires babel-runtime/regenerator when you use generators/async functions.
  • Automatically requires babel-runtime/core-js and maps ES6 static methods and built-ins.
  • Removes the inline babel helpers and uses the module babel-runtime/helpers instead.

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 babelPreprocessor config, viz.:

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

Aphaeresis answered 11/3, 2015 at 4:31 Comment(3)
I tried both options. Neither one worked for me. I added node_modules/babel/polyfill.js and Error: Uncaught ReferenceError: module is not defined. I believe referring to the single line in this file containing module. I added more and more dir/*.js directories and just got deeper into it with nothing working. The second option you listed seems to have no impact, same error.Acquisition
Your answer is very close and certainly put me on the right track. There are a few gotcha's so I posted an answer to help identify them.Acquisition
Awesome! I've edited the polyfill path in my answer to avoid confusing others.Aphaeresis
P
45

Node js Env - updated December 2015

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

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:

npm install babel-polyfill --save

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

require("babel-polyfill");

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

Pontiff answered 10/12, 2015 at 6:56 Comment(1)
I was trying to get FuseBox working to bundle a React app and I had to do this to get it working properly.Orcutt
Q
31

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.

@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:

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

These additions give ES6 authoring functionality without the ReferenceError.

Quanta answered 10/12, 2018 at 20:3 Comment(2)
I was trying to get some Jest unit tests to run correctly on circleci and had to use this to get them to pass.Rom
Works with webpack 5 + babelBoneyard
A
27

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

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

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,

The runtime optional transformer does three things:

  • Automatically requires babel-runtime/regenerator when you use generators/async functions.
  • Automatically requires babel-runtime/core-js and maps ES6 static methods and built-ins.
  • Removes the inline babel helpers and uses the module babel-runtime/helpers instead.

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 babelPreprocessor config, viz.:

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

Aphaeresis answered 11/3, 2015 at 4:31 Comment(3)
I tried both options. Neither one worked for me. I added node_modules/babel/polyfill.js and Error: Uncaught ReferenceError: module is not defined. I believe referring to the single line in this file containing module. I added more and more dir/*.js directories and just got deeper into it with nothing working. The second option you listed seems to have no impact, same error.Acquisition
Your answer is very close and certainly put me on the right track. There are a few gotcha's so I posted an answer to help identify them.Acquisition
Awesome! I've edited the polyfill path in my answer to avoid confusing others.Aphaeresis
A
4

I modified karma.conf.js to add browser-polyfill as mentioned in the Docs Link:

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:

  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);
    });
  });
Acquisition answered 11/3, 2015 at 14:1 Comment(2)
how does your whole karma.conf look like?Precipitin
The file to include seems to have turned into 'node_modules/babel-polyfill/browser.js'Heathcote
G
0

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

yarn add --dev react-app-polyfill

Then add the following lines to 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.

Gregorio answered 30/5, 2019 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.