exports 和 module.exports 二者的关系
1.module.exports才是真正的接口,exports只不过是它的一个辅助工具,最终返回给调用的是module.exports而不是exports。module.exports 初始值为一个空对象 {},而exports为指向module.exports 的引用
2. 在require() 的时候,返回的是 module.exports 而不是 exports
用一句话来说明就是,require方能看到的只有module.exports这个对象,它是看不到exports对象的,而我们在编写模块时用到的exports对象实际上只是对module.exports的引用。
代码示例
let a=1
exports.a=a
在index1中定义一个变量a,并用exports抛出
let a=require("./index1");
console.log(a);
在index2中引用并打印,可以看到打印出的就是对象{a:1}
这个时候如果我们在index1中修改成以下代码
let a=1
exports.a=a
module.exports={name:'123'}
此时再执行index2中的打印语句,就可以看到打印出来的是{name:‘123’}
这也证实了上面的论述。require方能看到的只有module.exports这个对象,它是看不到exports对象的,而我们在编写模块时用到的exports对象实际上只是对module.exports的引用
注意:
使用exports,只能单个设置属性 exports.a=a
使用module.exports,可以单个设置属性,也可以整个赋值
导出的模块仅执行一次
let a=require("./index1");
let b=require("./index1");
console.log(a==b);
输出的是true,说明一个模块中的JS代码仅在模块第一次被使用时执行一次,并且在使用的过程中进行初始化,之后缓存起来便于后续继续使用