Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: regeneratorRuntime is not defined (but working inside a scope)

Tags:

I' ve come across this strange occurrence of:

ReferenceError: regeneratorRuntime is not defined

... which I've managed to reproduce in a very minimal setting (compared to similar SO questions on the same issue), and also noticed some weird behavior depending on whether scopes are used.

The following code works:

'use strict';  require('babel-polyfill');  {  // scope A (if you remove it you observe different behavior when .babelrc is present)      function *simplestIterator() {         yield 42;     }      for (let v of simplestIterator()) {         console.log(v);     }  } 

Packages are:

$ npm ls --depth 0 [email protected] /home/mperdikeas/regeneratorRuntimeNotDefined ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] └── [email protected] 

Contents of .babelrc are:

$ cat .babelrc  {     "presets": ["es2016"] } 

However, when the scope is removed and the simplestIterator is placed on the global scope it fails with:

ReferenceError: regeneratorRuntime is not defined 

Even more strangely, if the .babelrc file is removed/renamed the code succeeds whether the scope is present or not. BTW whether it is scope or an IIFE that encapsulates the generator makes no difference.

Minimal github repo demonstrating this behavior here.

To observe the behavior:

git clone https://github.com/mperdikeas/regeneratorRuntimeNotDefined.git cd regeneratorRuntimeNotDefined/ npm install npm run build && npm run start 

The above will output 42 on the console. Now remove the scope and see what happens. Then rename .babelrc to see it working again (with or without scope).

My questions are:

  • why does the es2016 Babel preset trigger this error
  • why does putting the generator in a scope solves the problem?

update

Based on the accepted answer, and since this was code for a module I was writing I ended up doing:

require('babel-polyfill'); module.exports = require('./app.js'); 
like image 659
Marcus Junius Brutus Avatar asked Apr 14 '16 09:04

Marcus Junius Brutus


1 Answers

Babel assumes that the polyfill will be loaded before anything else in your application, but you're using a function declaration, which is hoisted, meaning that it exists and is usable before require has been called.

In the case of generators, then need regeneratorRuntime which is provided by the polyfill, but the polyfill hasn't loaded when the regenerator is initialized.

The Babel team's recommendation is to make two files:

index.js

require('babel-polyfill'); require('./app'); 
like image 66
loganfsmyth Avatar answered Sep 23 '22 13:09

loganfsmyth