How to deal with cyclic dependencies in Node.js

后端 未结 13 1950
别那么骄傲
别那么骄傲 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:10

    [EDIT] it's not 2015 and most libraries (i.e. express) have made updates with better patterns so circular dependencies are no longer necessary. I recommend simply not using them.


    I know I'm digging up an old answer here... The issue here is that module.exports is defined after you require ClassB. (which JohnnyHK's link shows) Circular dependencies work great in Node, they're just defined synchronously. When used properly, they actually solve a lot of common node issues (like accessing express.js app from other files)

    Just make sure your necessary exports are defined before you require a file with a circular dependency.

    This will break:

    var ClassA = function(){};
    var ClassB = require('classB'); //will require ClassA, which has no exports yet
    
    module.exports = ClassA;
    

    This will work:

    var ClassA = module.exports = function(){};
    var ClassB = require('classB');
    

    I use this pattern all the time for accessing the express.js app in other files:

    var express = require('express');
    var app = module.exports = express();
    // load in other dependencies, which can now require this file and use app
    

提交回复
热议问题