我在 Node.js 模块中找到了以下写法:
module.exports = exports = nano = function database_module(cfg) {...}
我想知道 module.exports 和 Exports 之间有什么区别以及为什么在这里使用两者。
您可以想象在文件的开头有类似的内容(仅用于解释):
var module = new Module(...);
var exports = module.exports;
因此,无论您做什么,请记住,当您从其他地方需要该模块时, 是 `module.exports` 而不是 `exports` 将从您的模块返回。
所以当你做类似的事情时:
exports.a = function() {
console.log("a");
}
exports.b = function() {
console.log("b");
}
您将 2 个函数 a 和 b 添加到 module.exports 指向的对象中,因此返回结果的 `typeof` 将是一个对象: { a: [Function], b: [Function] }
当然,如果您在此示例中使用 module.exports 而不是导出,则会得到相同的结果。
在这种情况下,您希望“module.exports”表现得像导出值的容器。 然而,如果您只想导出构造函数,那么您应该了解有关使用“module.exports”或“exports”的一些知识; (再次记住,当您需要某些内容时,将返回“module.exports”,而不是“export”)。
module.exports = function Something() {
console.log('bla bla');
}
现在 typeof 返回结果是“function”,您可以需要它并立即调用,如下所示:
var x = require('./file1.js')(); 因为你将返回结果覆盖为函数。
但是,使用导出时,您不能使用以下内容:
exports = function Something() {
console.log('bla bla');
}
var x = require('./file1.js')(); //Error: require is not a function
因为有了exports,引用不再指向module.exports 指向的对象,因此exports 和module.exports 之间不再有关系。 在这种情况下, module.exports 仍然指向将返回的空对象 {} 。
总结
- exports : 是文件初始化时生成的本地变量,即:一个空对象 {}
- 最初 module.exports (默认初始化时)是指向 exports 对象的。
- 只有 module.exports 才会被作为结果返回。
- 如果 module.exports 被指定或赋予了新的值,则新的值将会被返回。此时 exports 本地对象将与 module.exports 失去连系。
// 可以这样写:
export.name = 'xxxx'
export.age = 30
// 还可以这样写:
module.export = function() {
//
}
javascript - module.exports vs exports in Node.js - Stack Overflow