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 below:
a.js (the main file run with node)
var ClassB = require("./b");
var ClassA = function() {
this.thing = new ClassB();
this.property = 5;
}
var a = new ClassA();
module.exports = a;
b.js
var a = require("./a");
var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
util.log(a.property);
}
module.exports = ClassB;
My problem seems to be that I can't access the instance of ClassA from within an instance of ClassB.
Is there a correct / better way to structure modules to achieve what I want? Is there a better way to share variables between modules?
A solution which require minimal change is extending
module.exports
instead of overriding it.a.js - app entry point and module which use method do from b.js*
b.js - module which use method do from a.js
It will work and produce:
While this code will not work:
a.js
b.js
Output:
Actually I ended up requiring my dependency with
not pretty, but it works. It is more understandable and honest than changing b.js (for example only augmenting modules.export), which otherwise is perfect as is.
Similar to lanzz and setect's answers, I have been using the following pattern:
The
Object.assign()
copies the members into theexports
object that has already been given to other modules.The
=
assignment is logically redundant, since it is just settingmodule.exports
to itself, but I am using it because it helps my IDE (WebStorm) to recognise thatfirstMember
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.
An other method I've seen people do is exporting at the first line and saving it as a local variable like this:
I tend to use this method, do you know about any downsides of it?
Try to set properties on
module.exports
, instead of replacing it completely. E.g.,module.exports.instance = new ClassA()
ina.js
,module.exports.ClassB = ClassB
inb.js
. When you make circular module dependencies, the requiring module will get a reference to an incompletemodule.exports
from the required module, which you can add other properties latter on, but when you set the entiremodule.exports
, you actually create a new object which the requiring module has no way to access.for your problem, you can use function declarations.
class-b.js:
class-a.js: