exports 和 module.exports 用法上的区别

首先要知道,exports 和 module.exports 是 node 支持的导出方式,那么这两个导出命令在用法上有啥区别呢?

这里直接通过两个简单的例子进行说明:

// hello1.js
// exports方式导出模块
exports.hello = function () {
  console.log('Hello World!');
};
// hello2.js
// module.exports 方式导出模块
module.exports = function () {
	console.log('Hello World');
}

使用require的方式分别引入上面两个模块:

// test.js
var hello1 = require('./hello1.js');
var hello2 = require('./hello2.js');

// 调用函数
hello1.hello(); 	// Hello World
hello2();			// Hello World

总结

exports 对象是当前模块的导出对象,用于导出模块公有方法和属性。别的模块通过 require函数使用当前模块时得到的就是当前模块的exports对象。

module 对象可以访问到当前模块的一些相关信息,模块导出对象默认是一个普通对象。

上面的话总结起来就是三点:

  • module.exports 初始值为一个空对象 {}
  • exports 是指向的 module.exports 的引用
  • require() 返回的是 module.exports 而不是 exports
发布了80 篇原创文章 · 获赞 135 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_37954086/article/details/102647545
今日推荐