What determines the order of `require` calls in babel-transpiled scripts?

狂风中的少年 提交于 2021-02-08 05:02:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37503707/what-determines-the-order-of-require-calls-in-babel-transpiled-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!