Tuesday 14 March 2017

Avoiding circular dependencies with Node require()?

My question is below, but it's also here on StackOverflow if you to want to answer there: http://ift.tt/2mo9STh question:I'm having a problem where I have an Electron app, we'll say contained in files index.html and app.js. app.js is included in index.html with a script tag.Within app.js, I use var ENGINE = require("./myGameEngine/"); which then requires different classes, each in their own file. It looks something like this:var myEngine = myEngine || {}; myEngine.ClassA = require('./src/ClassA.js'); myEngine.ClassB = require('./src/ClassB.js'); myEngine.ClassC = require('./src/ClassC.js'); module.exports = myEngine; Unfortunately, sometimes ClassA, needs to use new myEngine.ClassB(). For example, if ClassA is an entity and has the function ClassA.addComponent() that function might require the use of var component = new myEngine.ClassB().When trying to do this, I run into an error that myEngine is undefined, even though it's the parent that required all these other files. I don't want to require it back in ClassB as that will create a circular dependency, but I need ClassB inside ClassA sometimes.What's most infuriating is that previously, instead of including app.js with script tags and requiring myEngine with require() I simply required both myEngine.js and app.js from the HTML file, and that all worked fine.I could go back to that system but I liked the simplicity of including a single JS file to go with my single HTML file, and doing all the requiring of the game engine inside that JS file, alongside modules from node_modules.Can someone explain to me how what the problem is here and how I can require files within a module, without having to redefine the module in every file?Thank you in advance!Edit: Regarding suggestions to include the classes within other classes, I have created a drawing about why I'd like to avoid that: Can of Worms

Submitted March 14, 2017 at 03:11PM by ianpaschal

No comments:

Post a Comment