内容提要
Node.js 模块遵循 CommonJS 规范:module.exports 用于导出值,默认是对象,也可覆盖为原始值;require 导入时得到的就是 module.exports。exports 只是 module.exports 的引用,可添加属性,但不能直接赋值覆盖,否则导出失效。
延伸解读
exports 与 module.exports 的关系
exports 只是 module.exports 的一个引用,初始时两者指向同一对象。因此,可以通过 exports 添加属性来导出内容,但不能直接给 exports 赋值,否则会断开引用,导致导出失效。理解这一点是避免常见错误的关键。
导出原始值的注意事项
module.exports 可以覆盖为原始值,如数字、字符串等。此时 require 导入的结果就是该原始值。但若使用 exports 来导出原始值,则必须通过 module.exports 赋值,因为直接给 exports 赋原始值会改变引用,导致导出为空对象。
实际使用中的常见错误
许多初学者会误用 exports = { s: 2 } 来导出对象,结果 require 得到空对象。正确做法是使用 module.exports = { s: 2 } 或 exports.s = 2。理解引用机制有助于避免这类错误,确保模块导出符合预期。
Q&A
Node.js 模块中 module.exports 和 exports 有什么区别?
module.exports 是模块导出的默认对象,可以覆盖为原始值;exports 只是 module.exports 的引用,可以添加属性,但不能直接赋值覆盖,否则导出失效。
为什么在 Node.js 中不能直接给 exports 赋值?
因为 exports 只是对 module.exports 的引用,直接赋值会断开引用,导致 exports 不再指向 module.exports,从而导出失效。
require 导入模块时得到的是什么?
require 导入模块时得到的就是 module.exports 的值,无论它是对象还是原始值。
如何正确使用 exports 导出多个属性?
可以通过 exports.属性名 = 值 的方式添加属性,例如 exports.s = 2,这样 require 得到的对象会包含这些属性。
module.exports 可以导出原始值吗?
可以,module.exports 可以覆盖为原始值,例如 module.exports = 2,require 导入时就会得到 2。
Node.js 模块的默认导出是什么?
Node.js 模块的默认导出是一个空对象,即 module.exports 默认为 {}。