module.exports和exports的区别

在node中,一个js模块其实是一个对象,可以通过console.log(module)打印出模块对象,如下:

Module {

      id: '.',

      exports: {},

      parent: null,

      filename: 'C:\\Users\...',

      loaded: false,

      children: [],

      paths: [

            'C:\\User\\Administrator\...',

            'C:\\node_modules\...'

      ]

}

其他js文件通过require()方法引用的时候,获取的其实就是exports属性,为了方便使用,node在每个模块中引入了exports变量,其实相当于在每个模块开头加入:

var exports = module.exports;

也就是说exports是对module.exports的一个引用,如果模块暴露过程中不直接对exports赋值,两者是等价的,例如:

//mod.js

exports.str = "string";    // 直接用exports暴露str参数

module.exports.str = "string";    //通过module.exports暴露str参数

//ext.js

var mod = require("./mod");    // 通过require引入mod.js模块

console.log(mod); // { str: "string" }

如果直接赋值给exports,相当于切断了两者的联系,其他js文件引用到的是module.exports属性的值,例如:

//mod.js

exports = "string from exports";    // 直接用exports暴露str参数

module.exports = "string from module.exports";    //通过module.exports暴露str参数

//ext.js

var mod = require("./mod");    // 通过require引入mod.js模块

console.log(mod); // "string from module.exports"

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容