How to deal with cyclic dependencies in Node.js

后端 未结 13 1932
别那么骄傲
别那么骄傲 2020-11-22 04:36

I\'ve been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following b

13条回答
  •  囚心锁ツ
    2020-11-22 05:14

    The solution is to 'forward declare' your exports object before requiring any other controller. So if you structure all your modules like this and you won't run into any issues like that:

    // Module exports forward declaration:
    module.exports = {
    
    };
    
    // Controllers:
    var other_module = require('./other_module');
    
    // Functions:
    var foo = function () {
    
    };
    
    // Module exports injects:
    module.exports.foo = foo;
    

提交回复
热议问题