solving circular dependency in node using requirejs

人盡茶涼 提交于 2019-11-29 08:02:57

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!