Difference between  exports  and  module.exports

Difference between exports and module.exports

·

2 min read

The module represents the current module in the plain Javascript object.

Exports is a plain JavaScript variable. Module is a plain javascript object which has the exports property

From one module to another, when we want to export a single class, variable, or function, we use modules. exports.

From one module to another, when we want to export multiple variables or functions, we use exports.

var module = { exports: { value1: 10 , value2: 20 } };
var exports = module.exports;

return module.exports;

In the above example, we have assigned multiple values to the same object.

module.exports.value1 returns 10 and module.exports.value2 returns 20

var module = { exports:  10  } };
var exports = module.exports;

return module.exports;

In the preceding example, exports is set to a value that results in modules.Exports are no longer the same object.

module.exports returns 10

const userDetails= (data)=>{
    return {
        getUsername:()=> data.username,
        getEmail:()=> data.email,
   }
}

module.exports = userDetails;

In the preceding example, calling userDetails(data>) returns the value of the username.getUsername()

const getUsername:(data)=> data.username

const getEmail:(data)=> data.email

exports.getUsername = getUsername;
exports.getEmail = getEmail;

In the above example the value of username can be got by getUsername()

If we go with the first approach, we do not need to include new lines in the export statement each time we create a new function.

Whereas in the second approach new functions if created gradually increases the number of lines of the exports statement as well

Therefore, as a best practice in accordance with the NodeJs documentation's usage of exports and module.exports, we can avoid using exports and instead use module.exports.

Thanks for reading ❤️. I hope you liked it.

Feel free to subscribe to my newsletter. Follow me via Twitter, Instagram, or Github.

Did you find this article valuable?

Support Dhanush N by becoming a sponsor. Any amount is appreciated!