循环导入,webpack返回空对象 [英] circular imports with webpack returning empty object
问题描述
目前遇到这个问题:
FileA:
var b = require file B
var c = require file C
FileB:
var a = require file A
FileC:
var a = require file A
当我运行代码时,我在文件C中收到错误:
When I run the code, I get an error in File C:
A.doSomething is not a function
在那里抛出一个调试器,看到A是一个空对象。什么是真的奇怪的是我只在文件C中收到错误,但不是文件B.在这里超级混淆。
Threw a debugger in there and saw that A is an empty object. What's really weird is that I'm only getting an error in File C, but not File B. Super confused here.
推荐答案
这不是webpack问题,而是CommonJS模块的属性。
This is not a webpack issue but a property of CommonJS modules.
首次需要CommonJS模块时,它的 exports
属性被初始化为幕后的空对象。
When a CommonJS module is first required, its exports
property is initialized to an empty object behind the scenes.
module.exports = {};
然后模块可以决定扩展此 exports
属性,或覆盖它。
The module can then decide to extend this exports
property, or override it.
exports.namedExport = function() { /* ... */ }; // extends
module.exports = { namedExport: function() { /* ... */ } }; // overrides
所以当 A
需要 B
和 B
需要 A
之后, A
不会再次执行(这将产生无限循环),但会返回其当前的 exports
属性。由于文件最顶部的 A
必需 B
,在导出任何内容之前,需要('A')
在 B
模块中调用将产生一个空对象。
So when A
requires B
and B
requires A
right after, A
is not executed again (which would produce an infinite loop), but its current exports
property is returned. Since A
required B
at the very top of the file, before exporting anything, the require('A')
call in the B
module will yield an empty object.
循环依赖的常见修复是将导入放在文件的末尾, 之后导出其他模块所需的变量。
A common fix for circular dependencies is to put your imports at the end of the file, after you've exported the variables needed by other modules.
A
:
module.exports = { foo: 'bar' };
require('B'); // at this point A.exports is not empty anymore
B
:
var A = require('A');
A.foo === 'bar';
这篇关于循环导入,webpack返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!