I\'ve found the following contract in a Node.js module:
module.exports = exports = nano = function database_module(cfg) {...}
I wonder what
why both are used here
I believe they just want to be clear that module.exports
, exports
, and nano
point to the same function - allowing you to use either variable to call the function within the file. nano
provides some context to what the function does.
exports
won't be exported (only module.exports
will), so why bother overwriting that as well?
The verbosity trade-off limits the risk of future bugs, such as using exports
instead of module.exports
within the file. It also provides clarification that module.exports
and exports
are in fact pointing to the same value.
module.exports
vs exports
As long as you don't reassign module.exports
or exports
(and instead add values to the object they both refer to), you won't have any issues and can safely use exports
to be more concise.
When assigning either to a non-object, they are now pointing to different places which can be confusing unless you intentionally want module.exports
to be something specific (such as a function).
Setting exports
to a non-object doesn't make much sense as you'll have to set module.exports = exports
at the end to be able to use it in other files.
let module = { exports: {} };
let exports = module.exports;
exports.msg = 'hi';
console.log(module.exports === exports); // true
exports = 'yo';
console.log(module.exports === exports); // false
exports = module.exports;
console.log(module.exports === exports); // true
module.exports = 'hello';
console.log(module.exports === exports); // false
module.exports = exports;
console.log(module.exports === exports); // true
module.exports
to a function?More concise! Compare how much shorter the 2nd example is:
helloWorld1.js:module.exports.hello = () => console.log('hello world');
app1.js: let sayHello = require('./helloWorld1'); sayHello.hello; // hello world
module.exports = () => console.log('hello world');
app2.js: let sayHello = require('./helloWorld2'); sayHello; // hello world