在 node中,module.exports和 exports区别

219 阅读2分钟

(懂的直接看最后)
首先让我们先看看官方文档

module.exports

A reference to the current module, see the section about the module object. In particular, module.exports is used for defining what a module exports and makes available through require().

module 对象是当前模块对象的引用,module.exports是有 Module 系统创建的,用来表示将从该模块中导出的内容

exports

  • A reference to the module.exports that is shorter to type.

  • The exports variable is available within a module's file-level scope, and is assigned the value of module.exports before the module is evaluated.

  • It allows a shortcut, so that module.exports.f = ... can be written more succinctly as exports.f = .... However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.exports:

    module.exports.hello = true;      // Exported from require of module
    exports = { hello: false };       // Not exported, only available in the module
    

exports 可以说是对 module.exports 的简写不为过, 该变量的作用域是文件级别的,和 module 作用域级别一样.

exports 和 module.exports 在默认情况下是指向同一个引用的(初始值为{}),即 exports 是对 module.exports 的引用

console.log(exports, module.exports, exports === module.exports);
//            {}           {}                 true    

也就是说修改exports 或者module.exports 任何一个的值都会导致另一个值的同步,也就是说你可以使用任意一个方式导出模块的内容, require(module)出来的内容就是 {a:2}

module.exports.a = 2;
console.log(exports, module.exports, exports === module.exports);
//           {a: 2}       {a: 2}             true

exports.a = 2;
console.log(exports, module.exports, exports === module.exports);
//           {a: 2}       {a: 2}             true

此刻,杠精上线

如果同时修改 module.exports 和 exports ,require(module)会导入什么内容呢?

exports.a = 2;
module.exports.a = 3;
console.log(exports, module.exports, exports === module.exports);
//           {a: 3}       {a: 3}              true
  • 为什么还是 exports === module.exports  为 true 呢?

  • 因为此刻修改的值只是修改了基本数据类型,并未修改值的引用,所以这两人的值并未变化

  • 那么同时修改值的引用后,我们看看 require(module)后的内容是什么?

  •   exports.a = 2;
      module.exports = { b: 3 };
      console.log(exports, module.exports, exports === module.exports);
      //           {a: 2}      {b: 3}              false
      
      然后我们打印 require(module) 后发现是 {b:3}
    

说明: 不管是 exports 还是 module.exports 导出内容,requeire 接受的模块内容是从 module.exports 对象导出的.

然后就是这两者导出的方式有点不同,
exports 只支持 使用.语法向外暴露内部变量,module.export 即支持.语法又支持直接复制一个对象的方式

讲了挺乱的,最后总结一番吧:

同: 

  • 两者皆可以向外暴露模块

  • 两者值的引用指向同一个地方

异:

  • require 只接受 module.exports 暴露的变量

  • exports 只支持.语法, module.exports 支持 .语法和直接赋值对象的形式

呼 ~  写完了,开开心心