gpt4 book ai didi

node.js - 使用 requirejs 解决 Node 中的循环依赖

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:45 27 4
gpt4 key购买 nike

我已经尝试了很多建议,我在谷歌上搜索了 Node 和 requirejs 中的循环依赖。不幸的是,我没有让它发挥作用。接近解决方案的尝试(我认为)如下:

// run.js
var requirejs = require('requirejs');

requirejs.config({
baseUrl: __dirname,
nodeRequire: require
});

requirejs(['A'], function(A) {
var a = new A.Go();
console.log(a.toon())
});


// A.js
define(['B', 'exports'], function(B, exports) {

exports.Go = function() {
var b = new require('B').Ho();
var toon = function() {
return 'me tarzan';
};

return {
b: b,
toon: toon
}
};
});


// B.js
define(['A', 'exports'], function(A, exports) {

exports.Ho = function() {
var a = new require('A').Go();
var show = function() {
return 'you jane';
}

return {
a: a,
show: show
}
};
});

在 Node 中运行此代码会导致 RangeError:超出最大调用堆栈大小我们从 A.js 中删除 B 的依赖,返回“me tarzan”

如有任何建议,我们将不胜感激!

最佳答案

循环引用很好,并不一定是糟糕设计的症状。您可能会争辩说,拥有许多微小的模块可能同样有害,因为代码/逻辑是分散的。

为了避免可怕的TypeError: Object #<Object> has no method您需要注意如何初始化 module.exports。我确信在 Node 中使用 requirejs 时也有类似的情况,但我没有在 Node 中使用过 requirejs 。

该问题是由 Node 对该模块的引用为空引起的。通过在调用 require 之前为导出分配一个值,可以轻松修复此问题。

function ModuleA() {
}

module.exports = ModuleA; // before you call require the export is initialized

var moduleB = require('./b'); //now b.js can safely include ModuleA

ModuleA.hello = function () {
console.log('hello!');
};

该样本来自https://coderwall.com/p/myzvmg哪里有更多信息。

关于node.js - 使用 requirejs 解决 Node 中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41759095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com