0

It is known that each module in Node.js is wrapped in a function, where 5 arguments are passed in (i.e. exports, module, require, __filename, __dirname) and the module.exports object is returned.

Since exports is just an alias for module.exports, is there a reason why both module and exports are listed as 2 separate arguments? Wouldn't it be better if it was just module object being passed in? This would prevent the exports object from being unintentionally reassigned if the user were to do a top-level reassignment (e.g. exports = {x: 5}).

In terms of design, is it simply for the ease of accessing the exports object? I feel like I'm missing out something here.

I couldn't find this question being answered, but I'm happy to be redirected to an existing one.

// function (exports, module, require, __filename, __dirname) {

const a = 1;
console.log(a);

// return module.exports;
// }
8

1 Answer 1

0

As node.js document said:

It allows a shortcut, so that module.exports.f = ... can be written more succinctly as exports.f = .... However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.export

module.exports.hello = true; // Exported from require of module
exports = { hello: false };  // Not exported, only available in the module

When the module.exports property is being completely replaced by a new object, it is common to also reassign exports:

module.exports = exports = function Constructor() {
  // ... etc.
};

https://nodejs.org/docs/latest/api/modules.html#exports-shortcut

1
  • 1
    Thanks @HDM91, I'm aware of what it does but I'm not sure why exporting has to be made available in 2 ways, apart from the fact that exports is more succinct.
    – Pottedtree
    Commented Dec 11, 2021 at 7:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.