Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

node.js - solving circular dependency in node using 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
    }
  };
});

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

Any suggestion is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...