module.exports和exports的区别

作者: 假装很会写代码 | 来源:发表于2017-07-03 13:01 被阅读6次

在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"

相关文章

网友评论

    本文标题:module.exports和exports的区别

    本文链接:https://www.haomeiwen.com/subject/ihgeqxtx.html