CommonJS Tools to solve Javascript Scope Issues using require() func and module object

For Javascript Scope problem, we used module object for export and require() function for import, but many of us don’t know this is also know as CommonJS.

The CommonJS group defined a module format to solve JavaScript scope issues by making sure each module is executed in its own namespace. To achieve this CommonJS gives you two tools:

  1. the require() function, which allows to import a given module into the current scope.
  2. the module object, which allows you to export something from the current scope.

Module definitions:

As it is, index.js will not work as MySalute is not defined. We need to define each script as a module:

// salute.js
var MySalute = "Hello";
module.exports = MySalute;
// index.js
var Result = MySalute + "world!";
module.exports = Result;

Here we make use of the special object module and place a reference of our variable into module.exports so the CommonJS module system knows this is the object of our module we want to show to the world. salute.js discloses MySalute, and index.js discloses Result.

Module dependency:

We’re near but there’s still a step missing: dependency definition. We’ve already defined every script as an independent module, but world.js still needs to know who defines MySalute:

// salute.js
var MySalute = "Hello";
module.exports = MySalute;
// index.js
var MySalute = require("./salute");
var Result = MySalute + "world!";
module.exports = Result;

Note that we didn’t use the full filename salute.js but ./salute when calling require, so you can omit the extension of your scripts. ./ means that the salute module is in the same directory as the world module.

At some places, we used exports as well as. So, is there any difference between exports and module.exports?

First Scenario
// salute.js
module.exports = "Hello";
// index.js
var MySalute = require("./salute");
console.log(MySalute);
Second Scenario
// salute.js
exports.a = "hello";
// index.js
var MySalute = require("./salute");
console.log(MySalute);

When you will run index.js file, in first Scenario, you will get output:

hello

In Second Scenario, you will get output:

{ a: 'hello' }

Because with this exports reference doesn’t ‘point’ anymore to the object where module.exports points, so there is not a relationship between exports and module.exports anymore. In this case module.exports still points to the empty object {} which will be returned.

You can reach out to me for any doubt and suggestions. Please share this with others as well.

Oh, and if you like this, click the 💚 below. Keep watching this space and follow me for more articles on technology.

Thanks!
Happy Coding!!