用webpack循环导入返回空对象
目前遇到这个确切的问题:
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
在那里扔了一个debugging器,看到A是一个空的对象。 真奇怪的是我只在文件C中出现错误,而不是在文件B中出现错误。
这不是一个webpack的问题,而是CommonJS模块的一个属性。
当首先需要CommonJS模块时,它的exports
属性被初始化为幕后的空对象。
module.exports = {};
然后模块可以决定扩展这个exports
属性,或覆盖它。
exports.namedExport = function() { /* ... */ }; // extends module.exports = { namedExport: function() { /* ... */ } }; // overrides
所以当A
需要B
和B
需要A
之后, A
不会再被执行(这将产生一个无限循环),但是它的当前的exports
属性被返回。 由于A
在文件的最顶部需要B
,所以在输出任何东西之前, B
模块中的require('A')
调用将产生一个空对象。
循环依赖的一个常见的解决方法是在导出其他模块所需的variables之后 ,将导入放在文件的末尾。
A
:
module.exports = { foo: 'bar' }; require('B'); // at this point A.exports is not empty anymore
B
:
var A = require('A'); A.foo === 'bar';