Wednesday, October 23, 2019

Pattern to solve circular dependencies in node,

This is an useful pattern to avoid circular dependencies while requiring other files in node.

Circular dependencies manifest when a require returns an empty object: "the circular dependency means that other code receives an incomplete module object"

The solution is to 'augment' the exports instead of replacing it. 
So, if another module got a reference to the exported members they are eventually completed.

//requires at the beginning, as usual
//.. 


const PublicMethods = {
 method1: () => {},
 method2: (x) => {...},
 ...
]; 

// -- private & other methods
... 
...

//augment the exports at the end of the file:
Object.assign(module.exports, PublicMethods);