4

我已经尝试了很多建议,我发现谷歌搜索 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
    }
  };
});

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

任何建议表示赞赏!

4

1 回答 1

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!');
};

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

于 2014-01-24T14:08:30.657 回答