Reputation: 19173
This is a problem I faced more than one. Here is an example file structure:
app.js
folder
-- index.js
-- module1.js
-- module2.js
From app.js
, the entry point of my application, I require folder/index.js
. This file itself is just a loader who requires all the other files in the directory. module1.js
and module2.js
both define some methods I want to use eventually. They are never directly required by app.js
since index.js
takes care of that and adds common helper utilities and applies some transformations to these modules.
All works well if I then use some methods defined in those files from app.js
after I required them. But the problem comes when a method defined in module2.js
wants to use a method defined in method1.js
(or vice-versa). Sometimes it will work, sometimes not (in folders with multiple files I didn't get to find out when precisely it works and when it doesn't yet).
If, from module2.js
I require ./index.js
and then use methods in it defined by module1.js
, I sometimes get Cannot read property 'myMethod' of undefined
. I assume it has to do with the order the modules are required by index.js
, but I can't seem to find a solution to this common problem (other than duplicating code or not using methods of these other modules).
Is there a common solution to this problem? I tried doing something like this :
var modules = require(./index.js);
exports.myMethod = function() {
if(!modules.module1 || !modules.module1.myOtherMethod) {
modules = require('./index.js');
}
modules.module1.myOtherMethod();
};
But it doesn't to do anything, modules.module1
is still undefined.
Upvotes: 0
Views: 270
Reputation: 396
You have a circular dependency problem. Try moving some of the common functions to a third file and have module1
and module2
require it, or make sure that one of them requires the other in one way only.
Never ever require a file that requires the current file back.
Upvotes: 0
Reputation: 60758
It just sounds like module
should require
module2
. That's the solution to module1
needing to call methods in module2
.
If you're worried about many calls to require
, don't. That's standard practice in every programming language I've used (in particular look at the import
statements in any Java program. Java is verbose, I know, but this is correct practice.)
It's definitely bad practice to look at code in one module and have no idea where anything comes from, because the require statements are missing.
Upvotes: 1