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

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

本文介绍了使用requirejs解决节点中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了许多建议,发现在节点和requirejs中使用循环依赖进行了谷歌搜索。不幸的是,我无法正常工作。下面是一个接近解决方案的尝试(我认为):

I have been try out many suggestions I found googling for circular dependency in node and requirejs. Unfortunately, I'm not getting it to work. The try which is closed to a solution (I think) is below:

// 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:最大调用堆栈大小超过
我们从A.js中删除了B的依赖项,并返回了 me tarzan

Running this code in node results in a RangeError: Maximum call stack size exceededWe the dependency of B is removed from A.js, 'me tarzan' is returned

任何建议都会受到赞赏!

Any suggestion is appreciated!

推荐答案

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

Circular references are fine and not necessarily a symptom of bad design. You might argue that having many tiny modules could be equally detrimental because code/logic is scattered.

为避免可怕的 TypeError:Object#<对象>没有方法,您需要注意如何初始化module.exports。我确定在节点中使用requirejs时也可以使用类似的方法,但是我没有在节点中使用requirejs。

To avoid the dreaded TypeError: Object #<Object> has no method you need to take some care in how you initialize module.exports. I'm sure something similar applies when using requirejs in node, but I haven't used requirejs in node.

问题是由节点的空引用引起的模块。通过在调用您的之前分配一个值可以很容易地解决此问题。

The problem is caused by node having an empty reference for the module. It is easily fixed by assigning a value to the exports before you call 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!');
};

此示例来自(其中提供了更多信息)。

This sample is from https://coderwall.com/p/myzvmg where more info available.

这篇关于使用requirejs解决节点中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:08