2

So, my workflow up to this point was to put

import "babel-polyfill";

when using features like async/await to ask babel to include the regenerator runtime in the transpilation.

I see the the following problems for users requiring my module:

  • The user is in an ES2015 environment and transpiles his code with babel-polyfill, too. Since babel-polyfill can only be required once, he will not be able to use my module at all.
  • If I thus choose not to include babel-polyfill, babel doesn't know that the module does require babel-polyfill and won't respect that in the generated require order (at least that's what I think happens).

I've recently created an npm module that does not come with babel-polyfill, but requires the user to include babel-polyfill before calling require on my npm module, since it uses async and await.

Thus, in my current project, I'd like to use my module like so in index.js:

import "babel-polyfill";
import Server from "./Server";
import foo from "bar";
import baz from "qux";

where Server is a class that extends my module that requires babel-polyfill.

However, the transpilation of index.js starts like this:

!function(e, r) {
  if ("function" == typeof define && define.amd)
      define(["bar", "qux", "./Server", "babel-polyfill"], r);
  else if ("undefined" != typeof exports)
      r(require("bar"), require("qux"), require("./Server"), require("babel-polyfill"));
  // etc.
}();

Here, I can clearly see that ./Server is required before babel-polyfill, although my ES2015 import syntax asks for the opposite. In fact, the entire order is mixed up.

That's why I'm getting the error:

ReferenceError: regeneratorRuntime is not defined

How can I tell babel to respect the order in my source?

Chiru
  • 3,661
  • 1
  • 20
  • 30
  • It's entirely possible that the order is just badly-handled. Not many people use the AMD output of Babel. When making redistributable modules, we generally recommend using `babel-runtime` over making users load the polyfill, but that also has trouble with AMD setups. – loganfsmyth May 28 '16 at 21:40
  • @loganfsmyth To be exact, I'm using the UMD output, just to support every environment. For now, I could work around this issue by creating a new file that only imports `babel-polyfill` and `index.js` (which is not a solution I'm happy with). With just two imports, the order seems correct. From what you're saying, it seems like making the bridge from `import` to `require` will rarely even be worth the effort in the future… – Chiru May 28 '16 at 22:14

1 Answers1

0

From what I can tell, you can't tell Babel to respect the order of your source - it will always hoist the imports and evaluate everything else afterwards. The only way seems to be switching to require when you want to ensure evaluation of some code (usually global assignments) first. As per my answer here.

Numerous issues raised (and closed/rejected) against Babel relating to this.

Community
  • 1
  • 1
Ben Logan
  • 166
  • 2
  • 9