【问题标题】:Assigning value to module.exports为 module.exports 赋值
【发布时间】:2016-06-17 13:44:09
【问题描述】:
我正在阅读 Node.js Design Patterns 中有关 module.exports 的信息。本书中提到:
重新分配exports变量没有任何效果,因为它不会改变module.exports的内容,它只会重新分配变量本身。
因此下面的代码是错误的:
exports = function() {
console.log('Hello');
};
我无法理解为什么上面的分配是错误的?
【问题讨论】:
标签:
javascript
node.js
commonjs
【解决方案1】:
您正在通过这样做覆盖本地 exports 变量。这是每个 Node.js 文件周围的 wrapper function 本地的。在您使用新对象时,V8 无法知道您对原始 exports 对象进行了哪些修改。
您要做的是覆盖module 对象中的exports 键。
module.exports = function() {
console.log('Hello');
};
为了更方便,您还可以分配给exports 变量,以便您可以在本地使用它:module.exports = exports = ...。这就是exports 的真正意义,一种访问module.exports 的更快方式。