是什么决定了babel编译脚本中"require"调用的顺序? [英] What determines the order of `require` calls in babel-transpiled scripts?
问题描述
所以,到目前为止,我的工作流程是
So, my workflow up to this point was to put
导入"babel-polyfill";
使用诸如 async
/ await
之类的功能要求babel在转译中包括再生器运行时.
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:
- 用户也处于ES2015环境中,并且还使用
babel-polyfill
转换其代码.由于babel-polyfill
只需要一次,因此他将完全无法使用我的模块. - 因此,如果我选择 not 来包含
babel-polyfill
,则babel不知道模块确实需要babel-polyfill
,并且不会在生成的require
顺序中尊重它(至少我认为是这样).
- The user is in an ES2015 environment and transpiles his code with
babel-polyfill
, too. Sincebabel-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 requirebabel-polyfill
and won't respect that in the generatedrequire
order (at least that's what I think happens).
我最近创建了一个npm模块,该模块不附带 babel-polyfill
,但要求用户在调用 require <之前先包含
babel-polyfill
/code>在我的npm模块上,因为它使用了 async
和 await
.
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
.
因此,在当前项目中,我想像在 index.js
中那样使用模块:
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";
其中 Server
是扩展我的模块的类,该模块需要 babel-polyfill
.
where Server
is a class that extends my module that requires babel-polyfill
.
但是, index.js
的转译是这样的:
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.
}();
在这里,我可以清楚地看到 ./Server
是之前 babel-polyfill
所必需的,尽管我的ES2015 import 代码>语法要求相反.实际上,整个订单是混乱的.
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
如何告诉babel尊重我的消息来源中的顺序?
How can I tell babel to respect the order in my source?
推荐答案
据我所知,您不能告诉Babel尊重货源的顺序-它将始终提升进口并随后评估其他所有货品.当您要确保首先评估某些代码(通常是全局分配)时,唯一的方法似乎是切换到要求.根据我的回答此处.
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.
针对Babel与此相关的众多问题.
Numerous issues raised (and closed/rejected) against Babel relating to this.
这篇关于是什么决定了babel编译脚本中"require"调用的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!