我正在使用 webpack + babel。我有三个模块,如下所示:
// 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
时,我看到以下内容:
B undefined
A
main some-const
如果我在 main.js
中交换导入,B
成为第一个,我得到:
A
B some-const
main some-const
为什么 B.js
得到 undefined
而不是第一个版本中的模块?怎么了?
最佳答案
经过将近一整天的工作来缩小问题范围(又名拉头发),我终于意识到我有一个循环依赖。
它说 //some other imports here
,A
导入另一个模块 C
,后者又导入 B
。 A
首先在 main.js
中导入,因此 B
最终成为“圆圈”中的最后一个链接,Webpack(或任何 CommonJS -like 环境,就此而言,例如 Node) 只是通过返回 A
的 module.exports
使其短路,它仍然是 undefined
.最终,它等于 some-const
,但是 B
中的同步代码最终处理的是 undefined
。
通过将 C
依赖的代码从 B
中移出,消除了循环依赖,解决了这个问题。希望 Webpack 能以某种方式警告我这一点。
编辑: 最后一点,正如@cookie 指出的那样,there's a plugin for circular dependency detection ,如果您想避免 [再次] 遇到此问题。
关于javascript - webpack import 返回 undefined,取决于导入的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35240716/