I have multiple JS classes in my project, and some of them are dependant on the others. Is it better to export from a module and use it as import in another module (or) create an instance of the class I need and use it as required(here I have an HTML file where I've included all the scripts I need)?
Am I missing any fundamental of export/import? Please feel free to correct.
PS: I'm using Node.js
Thank You
Top comments (4)
I cannot give concrete recommendations here, but I find myself using these signals: Scrolling and File Switching.
If you find yourself scrolling and switching between files less often, you are more likely moving in the right direction.
This is fantastic advice. Easy to remember. Easy to implement.
Thank You.
In the places where I've worked using JavaScript we've tended to use the method "export from a module and use it as import in another module". So if you want a quick answer this is what I would go for.
For the longer answer, there are pros and cons for each.
The second method sounds to me like dependency inversion. Dependency inversion is one of the SOLID principles. It means that we would have a special module purely to instantiate our other modules and their dependencies. For example, in your question, we would import the two modules there, instantiate the first one, and then instantiate the second one while passing in the first instance as a dependency. E.g.
const secondModuleInstance = new SecondModule(firstModuleInstance);
. That way our normal modules do not import and instantiate their dependencies directly.Dependency injection is a way to automagically do dependency inversion. All the instantiations are done automagically for us and we just specify what dependencies everything has in some configuration file. An example package for this is InversifyJS.
Benefit of dependency inversion:
Cost of dependency inversion:
Overall, in the scope of JavaScript applications, I don't believe things change frequently enough (the main motivation for dependency inversion) to justify the cost of implementing and using dependency inversion / injection.
An additional point. I recommend learning a bit more about programming principles and / or clean code practices. Even if you don't use them (e.g. we don't tend to use dependency inversion in JavaScript), knowing about them will make you a better programmer and better able to answer questions like these when they crop up in your projects.
I recommend the programming first principles series (disclaimer: I wrote it) or popular books such as Clean Code and Code Complete.
Thank you for explaining in detail. I'll surely go through your series.