solving circular dependency in node using requirejs

前端 未结 1 1614
夕颜
夕颜 2020-12-18 08:59

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

相关标签:
1条回答
  • 2020-12-18 09:38

    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.

    0 讨论(0)
提交回复
热议问题