2

I have an app that I'm working on that is three separate modules. All three modules will be packaged separately and stored in a private NPM repository. So each module will have it's own index.js, package.json, etc.

Module A depends on Module B and Module C. Module B depends on Module C.

Dependency Chart

Because Module A and Module B both have a dependency on Module C, will they share the dependency?

For instance, let's say that Module C has a singleton.js file that returns a singleton.

singleton.js

class MyClass {

}

const instance = new MyClass();

module.exports = instance;

And then the index.js for Module C exports that as well.

const myClassSingleton = require('./lib/singleton.js')

module.exports = myClassSingleton;

If both Module A and Module B require Module C

const moduleC = require('module-c');

Are they both sharing that same instance of that Singleton?

Spark323
  • 1,525
  • 2
  • 16
  • 27
  • 2
    Depends on the resolved path of the files being required. If they have each have their own copy of `module-c` in their own `node_modules` directory, then no. So it's not guaranteed, and will be on the whim of the package manager you use. https://stackoverflow.com/questions/13179109/singleton-pattern-in-nodejs-is-it-needed – Matt Feb 04 '21 at 22:16
  • I use it when I am in control of the require path, so inside a single app/module. – Matt Feb 04 '21 at 22:17
  • 1
    Across modules it should be less troublesome if you setup the code to inject the shared instance at initialisation. – Matt Feb 04 '21 at 22:17
  • Also tools like babel will add another layer of indirection/complexity to the answer. – Matt Feb 04 '21 at 22:20
  • @Matt, thanks. I'm trying to read more into this. I noticed sometimes that my modules have their own `node_modules` while other times they seem to just share the top level `node_modules` folder. It seems like it's dependent on that, as you suggest. How does NPM/Node determine if they will have their own `node_modules` folder or share the top level one? Does it have to do with versioning? – Spark323 Feb 04 '21 at 23:17
  • Versioning definitely requires different files, but it's changed so much over npm versions and yarn I wouldn't try to answer. There's always going to be some caveat with npm. If you can supply a bit more detail of what your doing between A/B/C people will probably be able to provide an alternative to using the module based singleton. – Matt Feb 05 '21 at 09:57

0 Answers0