How to deal with cyclic dependencies in Node.js

后端 未结 13 2136
别那么骄傲
别那么骄傲 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 04:57

    The important thing is not to re-assign the module.exports object that you have been given, because that object may have already been given to other modules in the cycle! Just assign properties inside module.exports and other modules will see them appear.

    So a simple solution is:

    module.exports.firstMember = ___;
    module.exports.secondMember = ___;
    

    The only real downside is the need to repeat module.exports. many times.


    Similar to lanzz and setec's answers, I have been using the following pattern, which feels more declarative:

    module.exports = Object.assign(module.exports, {
        firstMember: ___,
        secondMember: ___,
    });
    

    The Object.assign() copies the members into the exports object that has already been given to other modules.

    The = assignment is logically redundant, since it is just setting module.exports to itself, but I am using it because it helps my IDE (WebStorm) to recognise that firstMember is a property of this module, so "Go To -> Declaration" (Cmd-B) and other tooling will work from other files.

    This pattern is not very pretty, so I only use it when a cyclic dependency issue needs to be resolved.

    It is fairly well suited to the reveal pattern, because you can easily add and remove exports from the object, especially when using ES6's property shorthand.

    Object.assign(module.exports, {
        firstMember,
        //secondMember,
    });
    

提交回复
热议问题