浅谈node中module.exports和exports的区别
其实module.exports和exports在大多数的时候还是一样的,在使用上没有任何区别。解释两者的区别你先明白以下三点:
1、每次require返回的是module.exports而不是exports;
2、module.exports指向的是一个空对象{};
3、exports是module.exports的一个语法糖。
下面就用代码举例看一下123456789101112131415var module = { exports : { a: 1 }}var exports = module.exports; //这里就是上述所说的exports指向module.exports,一个语法糖console.log(module.exports.a); // 1console.log(exports.a); // 1上面的代码可以看书大多数时候module.exports和exports的用法并没有什么差别,但是有一个地方需要注意exports = {//这里把exports的引用指向一个新的对象,破坏了原来的引用关系 a : 2}console.log(module.exports.a); // 1console.log(exports.a); // 2
这里总结一下,为了避免出错,建议在项目中任何时候都使用module.exports是绝对不会出错的,同时不要轻易的去变更exports的引用地址。