Javascript WebPack将模块解析为对象而不是函数
我在同一个目录中有Javascript WebPack将模块解析为对象而不是函数,javascript,webpack,Javascript,Webpack,我在同一个目录中有entry point.js,First.js,Second.js 入口点.js var First = require('./First.js'); // If I take out this line the error will go away. var Second = require('./Second.js'); Second(); var Second = require('./Second.js'); // And if I take out this li
entry point.js
,First.js
,Second.js
入口点.js
var First = require('./First.js'); // If I take out this line the error will go away.
var Second = require('./Second.js');
Second();
var Second = require('./Second.js'); // And if I take out this line the error will go away.
module.exports = () => {
console.log('FIRST')
};
var First = require('./First.js');
module.exports = () => {
First();
};
First.js
var First = require('./First.js'); // If I take out this line the error will go away.
var Second = require('./Second.js');
Second();
var Second = require('./Second.js'); // And if I take out this line the error will go away.
module.exports = () => {
console.log('FIRST')
};
var First = require('./First.js');
module.exports = () => {
First();
};
Second.js
var First = require('./First.js'); // If I take out this line the error will go away.
var Second = require('./Second.js');
Second();
var Second = require('./Second.js'); // And if I take out this line the error will go away.
module.exports = () => {
console.log('FIRST')
};
var First = require('./First.js');
module.exports = () => {
First();
};
当我用一个非常基本的网页配置编译entry point.js
时(实际上没有什么,我甚至不想用它来污染问题),我首先得到的错误是不是一个函数
。我想这是因为存在一些递归依赖关系,但我不能完全理解这一点
另外,我知道如何修复它,我只是想知道它为什么不工作。你的问题是循环依赖性:
第一个
依赖于第二个
和第二个
依赖于第一个
这是由于存在依赖循环,并且正在将module.exports
分配给文件末尾的新对象
由于循环的原因,module.exports
对象被传递到first
第一行的Second
,这是一个空对象
在此之后,First
重新分配模块的值。导出
到函数,但对象已传递到Second
,这就是为什么会出现错误
若要解决此问题,请尽可能消除循环依赖关系。循环依赖是令人困惑的,并且通常是紧密耦合代码的症状,最好以将常见依赖提取到它们自己的模块的方式对函数进行模块化
如果无法消除循环依赖项,则需要避免重新分配模块.exports
First.js:
Second.js
当您在
入口点中需要第一个,加载程序开始加载第一个.js
,这需要第二个.js
。由于第一个
没有完全完成加载,因此它是一个空对象,这就是为什么得到的不是一个函数
错误
有很多方法可以解决循环依赖性问题。一种方法是添加一个包含所有导入的文件,然后从中请求
//dependecy.js
var First = require("./First")
var Second = require("./Second")
exports.First = First
exports.Second =Second
//First.js
var {Second} =require("./dependency")
//Second.js
var {Frist} =require("./dependency")