Do you remember the syntax of the function wrapper that the code inside each module gets converted to? Well, it is provided here again for your reference.
(function(exports, require, module, __filename, __dirname) { // Module code actually lives in here });
We discussed the require and module parameters. It’s now time to discuss the exports parameter and understand what it does. Let’s look at it in the next video.
In the next video, you will see how the exports variable is a shortcut to module.exports.
In the last video, you learnt the following facts:
1. The exports keyword is a shortcut to using module.exports.
2. exports is a variable that references the module.exports object.
3. Before the code in a module is evaluated, the exports variable is assigned the reference to the module.exports.
4. At the end of each module, module.exports is returned. Thus, the require function in some other module loads the object returned by the module.exports keyword.
5. Objects in JavaScript are passed by reference.
6. When a property is changed in an object, which points to (references) another object, the change is reflected in the pointed (referenced) object. The exports variable points to the module.exports object. Thus, if you make a change in a property using the exports variable, the change is reflected in the module.exports object.
exports = module.exports;
Let’s assume that module.exports consists of the following object:
{a: 1, b: 2}
Output (State of exports and module.exports):
exports
{a: 1, b: 2}
module.exports
{a: 1, b: 2}
Now, execute the following statement:
exports.x = 100;
Output (State of exports and module.exports):
exports
{a: 1, b: 2, x: 100}
module.exports
{a: 1, b: 2, x: 100}
Here, exports and module.exports consist of the same value.
7. When an object pointing to (referencing) another object is assigned a new value (object), then the changes are not reflected in the pointed (referenced) object. When the exports variable is assigned a value, which is a new object, the module.exports object is not changed, i.e., it remains as it was.
exports = module.exports;
Let’s assume that module.exports consists of the following object:
{a: 1, b: 2}
Output (State of exports and module.exports):
exports
{a: 1, b: 2}
module.exports
{a: 1, b: 2}
Now, execute the following statement:
exports = {x: 100};
Output (State of exports and module.exports):
exports
{x: 100}
module.exports
{a: 1, b: 2}
Here, exports and module.exports do not consist of the same value.