关于Node.js中的exports和module.exports,不少时候都比较容易让人混淆,弄不清楚二者间的区别。那么咱们就从头开始理清这二者之间的关系。javascript
在开发Node.js应用的时候,不少模块都是须要引入才能使用,可是为何exports和module.exports咱们没有引用却能够直接使用呢?java
事实上,Node.js应用在编译的过程当中会对JavaScript文件的内容进行头尾的封装。例如:ui
// hello.js
const hello = function () {
console.log('Hello world');
}
module.exports = {
hello
}
// 头尾封装后的js代码
(function (exports, require, module, __filename, __dirname) {
const hello = function () {
console.log('Hello world');
}
module.exports = {
hello
}
})
复制代码
在进行了头尾封装以后,各个模块之间进行了做用域隔离,避免了污染全局变量,同时能够使每一个模块在不引入这些变量的状况下能够使用它们。这些变量依次为当前模块的exports属性、require()方法、当前模块自身(module)、在文件系统中的完整路径、文件目录。spa
按照Node.js的解释,exports是module对象的一个属性,那么exports和module.exports应该是等价的。的确如初,初始化的exports和module.exports变量的值均为{},代码验证:code
// hello.js
const hello = function () {
console.log('Hello world');
}
console.log('初始值==========');
console.log(exports);
console.log(module.exports);
module.exports = {
hello
}
// 输出结果
初始值==========
{}
{}
复制代码
能够发现,module对象的exports属性和exports均指向一个空对象{},那么在导出对象的时候使用exports和module.exports有什么区别呢?对象
咱们在使用require()方法引入模块的时候,实际上是引入了module.exports对象, exports只是module对象的exports的一个引用,咱们能够经过修改exports所指向对象的值来协助修改module.exports的值。ip
const hello = function () {
console.log('Hello world');
}
exports.hello = {
hello
}
console.log('修改值==========');
console.log(exports);
console.log(module.exports);
// 输出结果
修改值==========
{ hello: { hello: [Function: hello] } }
{ hello: { hello: [Function: hello] } }
复制代码
因为exports和module.exports指向同一块内存区域,因此咱们修改exports对象的数据,那么module.exports也会随之改变。内存
// hello.js
const hello = function () {
console.log('Hello world');
}
module.exports = {
hello
}
console.log('修改值==========');
console.log(exports);
console.log(module.exports);
// 输出结果
修改值==========
{}
{ hello: [Function: hello] }
复制代码
你会发现修改后的exports依然是{},而module.exports的值已经改变,这是因为当你给module.exports是直接等于一个新的对象,那么其将指向一块新的内存区域,而此时exports指向的仍然是以前的内存区域,因此两者的值会不同,可是此时你在其余文件内引入hello.js文件,仍然能够调用hello()方法,这也说明了导出的是module.exports而不是exports。作用域
// hello.js
const hello = function () {
console.log('Hello world');
}
exports = {
hello
}
console.log('修改值==========');
console.log(exports);
console.log(module.exports);
// 输出结果
修改值==========
{ hello: [Function: hello] }
{}
复制代码
使用这种方法导出在其余文件调用hello方法即会报错,由于该文件模块导出的对象为空,固然也不可能有hello()方法,这种问题的缘由一样是指向的内存区域发生变化所致使的。开发