简体   繁体   中英

Difference between module.exports in node

What is the difference between

module.exports = UpgradeService;

and

module.exports = { UpgradeService };

When I used the second one, I wasn't able to peek its definition in VS code. Why this is happening and what are the similarities and differences between them?

The first statement sets the exported value to UpgradeService . The second statement sets the exported value to an object. The { UpgradeService } is a shorthand for { UpgradeService: UpgradeService } which is a simple key:value pair! In other words, it exports a plain object that has only one (own) key: UpgradeService .

Remember that setting module.exports = (something) really is just changing what you get when you require() the module, and that (something) can be any value. You could set module.exports = 42 and require() would return the number 42 just fine.

Doing module.exports = { UpgradeService } means that you're setting the export to an object , which looks like {"UpgradeService": UpgradeService} . That follows the ES6 syntax rule where {x, y} is the same as {x: x, y: y} .

Then in your other files, instead of doing const UpgradeService = require('blah') , you do const UpradeService = require('blah').UpradeService , or const { UpgradeService } = require('blah') with destructuring .

Usually you set module.exports to an object (instead of a function or class) when you plan on exporting multiple things. For example, you might want to export both UpgradeService and, later, a new Upgrade class; in that case, you would do module.exports = { UpgradeService, Upgrade } .

Some people prefer to always start with exporting an object like that, because then it's easy to add a new exported thing. For instance, if you change module.exports = 'Apple' to module.exports = { fruit: 'Apple', animal: 'Bat' } , you have to change all files which required that module. But if you had just started with module.exports = { fruit: 'Apple' } , you would be able to add animal: 'Bat' without having to change any existing files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM