The content of this article is about the differences and connections between exports and module.expors? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In our modular development, we must use these two things exports/module.exports to export variables or functions. Because each module in modular development has its own module scope.
For example:
//a.js var foo = '苏小猫'
//b.js console.log(foo)
We cannot access the foo variable in a.js in b.js, so the output of b.js is "undefine". If we want to access the foo variable in a.js in the b.js module, we must export the foo variable in a.js using exports or module.exports.
For example, the relationship and difference between
//a.js var foo = '苏小猫'; module.exports = foo;
//b.js var foo = require('./b.js'); console.log(foo);
During development, we were very confused about whether to use exports or module.exports. In fact, exports and module.exports are the same thing, and exports is just a reference to module.exports. exports are equivalent to module.exports. We can test it in node.
Each module ultimately returns return module.exports;
In our normal understanding, export a single variable or a single Use module.exports for functions;
module.exports = function(){ console.log("在你心里种点Bnum") } //我们require之后就会得到一个[Function]
To export multiple variables, use exports;
exports.name = "苏小猫" exports.tree = function(){ console.log("在你心里种点Bnum") } //我们require之后就会得到一个对象{name:"苏小猫",tree:[Function]}
exports and module.exports themselves are empty objects, and exports.xxx is equivalent to adding them to an object. thing.
Why does module.exports export a single one?
Because it is originally an empty object, module.exports=xxx. Now you reassign it, so it only exports this xxx.
If you reassign exports (exports={}), its meaning will be different; now exports is different from module.exports There is no longer a half-cent relationship, exports.xxx = xxx; adding things to it will no longer affect the final return module.exports.
Look, age no longer enters the final return module.exports.
If you still want to continue using exports.xxx, you have to re-assign module.exports to exports.
Look, it’s working again now.
If you are confused whether to use exports or module.exports during development, then forget exports (forget it, we don’t need a spare tire, hahahaha).
As I said at the beginning, exports itself is a reference to module.exports. module.exports can do everything exports can do. For example, export multiple variables or functions.
The above is the detailed content of What are the differences and connections between exports and module.expors?. For more information, please follow other related articles on the PHP Chinese website!