目前正遇到这个确切的问题:
FileA:
var b = require file B
var c = require file C
FileB:
var a = require file A
FileC:
var a = require file A
当我运行代码时,文件 C 中出现错误:
A.doSomething is not a function
在那里扔了一个调试器,发现 A 是一个空对象。 真正奇怪的是,我只在文件 C 中收到错误,而不是在文件 B 中。这里 super 困惑。
最佳答案
这不是 webpack 的问题,而是 CommonJS 模块的属性。
当第一次需要一个 CommonJS 模块时,它的 exports
属性在后台被初始化为一个空对象。
module.exports = {};
然后模块可以决定扩展这个 exports
属性,或者覆盖它。
exports.namedExport = function() { /* ... */ }; // extends
module.exports = { namedExport: function() { /* ... */ } }; // overrides
所以当 A
需要 B
并且 B
需要 A
之后,A
不会再次执行(这会产生无限循环),但会返回其当前的 exports
属性。由于 A
在文件的最顶部需要 B
,因此在导出任何内容之前, 中的
模块将产生一个空对象。require('A')
调用B
循环依赖的一个常见解决方法是将导入放在文件末尾,在您导出其他模块所需的变量之后。
A
:
module.exports = { foo: 'bar' };
require('B'); // at this point A.exports is not empty anymore
B
:
var A = require('A');
A.foo === 'bar';
关于javascript - webpack 循环导入返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30378226/