ReferenceError: regeneratorRuntime is not defined (but working inside a scope)
<p>I' ve come across this strange occurrence of:</p>
<p><code>ReferenceError: regeneratorRuntime is not defined</code></p>
<p>... 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.</p>
<p>The following code works:</p>
<pre><code>'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);
    }

}
</code></pre>
<p>Packages are:</p>
<pre><code>$ npm ls --depth 0
simple-babel-serverside-node-only-archetype@1.0.0 /home/mperdikeas/regeneratorRuntimeNotDefined
├── babel-cli@6.7.5
├── babel-core@6.7.6
├── babel-polyfill@6.7.4
├── babel-preset-es2016@6.0.11
└── babel-runtime@6.6.1
</code></pre>
<p>Contents of <code>.babelrc</code> are:</p>
<pre><code>$ cat .babelrc 
{
    &quot;presets&quot;: [&quot;es2016&quot;]
}
</code></pre>
<p>However, when the scope is removed and the <code>simplestIterator</code> is placed on the global scope it fails with:</p>
<pre><code>ReferenceError: regeneratorRuntime is not defined
</code></pre>
<p>Even more strangely, if the <code>.babelrc</code> 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.</p>
<p>Minimal github repo demonstrating this behavior <a href="https://github.com/mperdikeas/regeneratorRuntimeNotDefined" rel="noreferrer">here</a>.</p>
<p>To observe the behavior:</p>
<pre><code>git clone https://github.com/mperdikeas/regeneratorRuntimeNotDefined.git
cd regeneratorRuntimeNotDefined/
npm install
npm run build &amp;&amp; npm run start
</code></pre>
<p>The above will output <code>42</code> on the console. Now remove the scope and see what happens. Then rename <code>.babelrc</code> to see it working again (with or without scope).</p>
<p>My questions are:</p>
<ul>
<li>why does the <code>es2016</code> Babel preset trigger this error</li>
<li>why does putting the generator in a scope solves the problem?</li>
</ul>
<h1>update</h1>
<p>Based on the accepted answer, and since this was code for a module I was writing I ended up doing:</p>
<pre><code>require('babel-polyfill');
module.exports = require('./app.js');
</code></pre>