在使用webpack时,两个文件在Javascript中是否可以相互依赖?
我有一个文件夹在使用webpack时,两个文件在Javascript中是否可以相互依赖?,javascript,dependencies,webpack,Javascript,Dependencies,Webpack,我有一个文件夹App,其中包含: index.html lib包含我的javascript(JS)文件的文件夹 我正在使用webpack捆绑我的JS文件,因此每个JS文件的顶部都需要它的依赖项(同一个lib文件夹中的其他JS文件),底部需要module.exports spaceship.js导出构造函数spaceship,而bullet.js导出构造函数bullet 然后我有一个JS文件factory.JS,它导出一个名为factory的对象。此对象包含一个名为CreateSpace的方法
App
,其中包含:
index.html
包含我的javascript(JS)文件的文件夹lib
spaceship.js
导出构造函数spaceship,而bullet.js
导出构造函数bullet
然后我有一个JS文件factory.JS
,它导出一个名为factory的对象。此对象包含一个名为CreateSpace的方法和另一个名为CreateBill的方法:
// Factory.js
var Bullet = require("./bullet.js");
var Spaceship = require("./spaceship.js");
var Factory {
createSpaceship: function() {
(...)
return new Spaceship();
},
createBullet: function() {
(...)
return new Bullet();
}
}
module.exports = Factory;
然而,在spaceship.js内部,有一个名为fireBullet的方法,它创建了Bullet的一个新实例。为此,我需要spaceship.js中的factory.js两个文件以这种方式相互需要是否有问题?
// spaceship.js
var Factory = require("./factory.js");
var Spaceship = function() {
//constructor
}
Spaceship.prototype.fireBullet = function() {
(...)
return Factory.createBullet();
}
我在spaceship.js中遇到了一个错误,比如
未捕获类型错误:Factory.CreateBill不是函数
我不知道webpack在技术上是如何工作的,因此我不能确定这是否是产生错误的原因。webpack以与Node相同的方式处理循环依赖项,因此支持循环依赖项--请参阅以了解限制 如前所述,通过重新设计通常可以避免循环依赖,但鉴于您当前的设计,您有两个选项可以修复循环依赖:
// Spaceship.js
var Factory = require('./Factory');
function Spaceship(name) {
// Re-require the factory during instantiation, this works because the factory module has since defined it's export.
Factory = require('./Factory');
this.name = name;
}
或者
// Factory.js
// Mutate the provided exports object instead of overriding `module.exports`. This works because Node knows what the export will be upfront. NOTE: like the first example the methods will only available in other modules after this module has returned.
exports.createSpaceship = function(name) {
return new Spaceship(name);
};
exports.createBullet = function(name) {
return new Bullet(name);
};
这不是一个循环引用吗?你怎么会要求a中的某个东西来自B,当a没有完成时,用a使B工作,因为它仍然使用B,哪个先来,鸡还是蛋?是的,我同意。我只是想从技术上确认一下,事实确实如此。