Why do I need to create a variable to store a module that is imported using require()?


#1

Question

Why do I need to create a variable to store a module that is imported using require()?

Answer

The module that’s imported has it’s own private scope as it’s wrapped in an object. We could access the module’s properties directly from the return value of require function (the imported module), however, this may make our code difficult to understand and read.
For example:
moduleToExport.js:

let MainObject = {};

MainObject.objToExport = {
  propOne: 1,
  propTwo: 2
};

MainObject.anotherObjToExport = {
  anotherProp: 3,
  andAnother: 4
};

module.exports = MainObject;

main.js:

console.log(require('./moduleToExport.js').objToExport.propOne); //logs `1` to the console

Instead of accessing a module’s properties directly from the return value of the require function, we should assign the imported module to a variable name, then access the properties via the variable, i.e.:

const myImportedModule = require('./moduleToExport.js');
console.log(myImportedModule.objectToExport.propOne); //logs `1` to the console