CommonJs 导出 exports 和 module.exports 的区别

120 阅读1分钟

exports 和 module.exports 的区别

  • exports关键字默认指向module.exports的内存空间
  • 若对exports重新赋值,则断开了exportsmodule.exports的指向,这里最主要是要知道指针的概念
  • require()返回的是module.exports而不是exports

导出的例子

  • 例1,正确用法
exports.name = "想半天"
// 上下赋值进的是同一个对象,因为他们本来就指向同一个地址
module.exports.height = 172
  • 例2,错误用法
exports.name = "想半天"
// 上面生效,下面不生效
// 因为对 export 赋值对象后断开了与当前模块导出对象(即 module.exports)的引用
exports = {
    height: 172
}
exports.weight = 118

总结图

image.png