Webpack导入返回不确定的,具体取决于导入的顺序 [英] Webpack import returns undefined, depending on the order of imports
问题描述
我正在使用webpack + babel.我有三个看起来像这样的模块:
I'm using webpack + babel. I have three modules looking like this:
// A.js
// some other imports here
console.log('A');
export default 'some-const';
// B.js
import someConst from './A';
console.log('B', someConst);
export default 'something-else';
// main.js
import someConst from './A';
import somethingElse from './B';
console.log('main', someConst);
执行main.js
时,我看到以下内容:
When main.js
is executed, I see the following:
B undefined
A
main some-const
如果我交换main.js
中的导入,而B
成为第一个,则会得到:
If I swap the imports in main.js
, B
becoming the first, I get:
A
B some-const
main some-const
B.js
为什么会得到undefined
而不是第一个版本中的模块?怎么了?
How come B.js
gets undefined
instead of a module in the first version? What's wrong?
推荐答案
在将问题缩小了整整一个工作日(又称拉头发)之后,我终于意识到我有一个循环依赖.
After almost a full workday of narrowing down the issue (AKA hair-pulling), I've finally came to realize that I have a circular dependency.
// some other imports here
的地方,A
导入另一个模块C
,该模块又导入B
. A
首先在main.js
中导入,所以B
最终成为圆"中的最后一个链接,而Webpack(或类似Node.com的任何类似CommonJS的环境)只是通过以下方式将其短路返回A
的module.exports
,仍然是undefined
.最终,它等于some-const
,但是B
中的同步代码最终改为处理undefined
.
Where it says // some other imports here
, A
imports another module C
, which, in turn, imports B
. A
gets imported first in main.js
, so B
ends up being the last link in the "circle", and Webpack (or any CommonJS-like environment, for that matter, like Node) just short-circuits it by returning A
's module.exports
, which is still undefined
. Eventually, it becomes equal to some-const
, but the synchronous code in B
ends up dealing with undefined
instead.
通过从B
中移出C
所依赖的代码,消除了循环依赖关系,从而解决了该问题.希望Webpack会以某种方式警告我.
Eliminating the circular dependency, by moving out the code that C
depends on out of B
, has resolved the issue. Wish Webpack would somehow warn me about this.
在最后一个注释上,如@cookie所指出的,循环依赖检测插件,如果您想避免再次遇到此问题.
On the last note, as pointed out by @cookie, there's a plugin for circular dependency detection, if you'd like to avoid hitting this problem [again].
这篇关于Webpack导入返回不确定的,具体取决于导入的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!