Imported modules as a Singleton

I have two modules:

  • MongoModule: one makes a bunch of Mongo queries and exports the fields on an object called Docs.
  • FunctionsMudule: one has a bunch of functions that act upon said module’s fields inside Docs.
  • FunctionThatUsesBothModules: I then have a function that uses both the MongoModule and the FunctionsModule.

I read that modules are Singletons, so if I import MongoModule into FunctionsModule AND FunctionThatUsesBothModules, i want to make sure I don’t make to different copies that query all that data twice. Is this how it works?

modules are singleton, but this is only relevant, if you alter an exported object, e.g.:

// module A
let myVar = "initial value"

export default {
   get: () => myVar,
   set: ( newVal ) => myVar = newVal
}

// module B
import a from './A';

a.get(); // is "initial value"
a.set("new value");
a.get(); // is "new value"

// module C
import a from './A';

a.get(); // is already "new value", because a is a singleton

But I don’t get how this affects your situation.

1 Like