4

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!

3
  • You should use the A and B constructors received by your function as first argument: 'new require('A').Go();' should read '(new A).Go()' (same for B, of course). I don't know if this is going to help with the circular dependency though. Commented Sep 28, 2012 at 12:53
  • @Sergio You are right, normally I would not do it like this. The API doc of requirejs suggest this method. When using (new B).Ho() it errors: TypeError: object is not a function, probably because B is unknown at that moment. Commented Sep 28, 2012 at 13:29
  • Oh, I didn't know about that case. Thanks for your correction. Commented Sep 28, 2012 at 14:50

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.