使用requirejs解决节点中的循环依赖

don*_*nut 4 circular-dependency node.js requirejs

我已经尝试了很多建议,我发现在谷歌上搜索 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
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

在节点中运行此代码会导致 RangeError: Maximum call stack size exceeded 我们从 A.js 中删除了 B 的依赖,返回了 'me tarzan'

任何建议表示赞赏!

Tom*_*rae 5

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

为避免出现这种情况,TypeError: Object #<Object> has no method您需要注意初始化 module.exports 的方式。我确定在 node 中使用 requirejs 时也有类似的情况,但我没有在 node 中使用 requirejs。

该问题是由节点对模块的引用为空引起的。通过调用 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!');
};
Run Code Online (Sandbox Code Playgroud)

此示例来自 https://coderwall.com/p/myzvmg,其中提供了更多信息。