You must be very familiar with the node. js ModuleExportsObject, you can use it to create your module. Example: (assume this is the rocker. js file)
exports.name = function() { console.log('My name is Lemmy Kilmister');};
In another file, you reference
var rocker = require('./rocker.js');rocker.name(); // 'My name is Lemmy Kilmister'
So farModule. ExportsWhat is it? Is it legal?
In fact,Module.exports
Is the real interface,ExportsIt is just an auxiliary tool. Which of the following statements is returned to the call?Module.exports
InsteadExports.
AllExportsThe collected attributes and methods are assignedModule.exports
. Of course, there is a premise thatModule.exports
It does not have any attributes or methods.
. If,
Module.exports
Some attributes and methods are available, so the information collected by exports will be ignored.
Modify rocker. js as follows:
module.exports = 'ROCK IT!';exports.name = function() { console.log('My name is Lemmy Kilmister');};
Reference and execute rocker. js again
var rocker = require('./rocker.js');rocker.name(); // TypeError: Object ROCK IT! has no method 'name'
Error reported: object "Rock it !" No name Method
The rocker module ignores the name method collected by exports and returns a string "Rock it !". We can see that your module does not have to return an "instantiated object ". Your module can be any legal JavaScript Object-Boolean, number, date, JSON, String, function, array, and so on.
Your module can be anything you set for it. If you do not explicitlyModule.exports
Set any attributes and methods, so your module is set to exportsModule. Exports
Attribute.
In the following example, your module is a class:
module.exports = function(name, age) { this.name = name; this.age = age; this.about = function() { console.log(this.name +' is '+ this.age +' years old'); };};
You can apply it as follows:
var Rocker = require('./rocker.js');var r = new Rocker('Ozzy', 62);r.about(); // Ozzy is 62 years old
In the following example, your module is an array:
module.exports = ['Lemmy Kilmister', 'Ozzy Osbourne', 'Ronnie James Dio', 'Steven Tyler', 'Mick Jagger'];
You can apply it as follows:
var rocker = require('./rocker.js');console.log('Rockin in heaven: ' + rocker[2]); //Rockin in heaven: Ronnie James Dio
Now you understand that if you want your module to be of a specific type, useModule.exports
. If the module you want is a typical "instantiated object ",Exports.
Adding properties to module. Exports is similar to adding properties to exports. For example:
module.exports.name = function() { console.log('My name is Lemmy Kilmister');};
Similarly, exports is like this.
exports.name = function() { console.log('My name is Lemmy Kilmister');};
Note that these two results are not the same. As mentioned above, module. exports is a real interface, and exports is only a helper tool. We recommend that you use exports for export, unless you want to change from the original "instantiated object" to a type.