exports 和 module.exports 的联系和区别

最近遇到了一次 exports 导出的 class 在其它文件中不能使用的问题,仔细检查,发现是导出的方式有问题。ui

在这里总结一下。spa

当时导出的方法是:对象

exports = class Test {it

...io

}function

而后在其它文件中,不管怎样都只能获得一个空对象。class

后来改为require

exports = module.exports = class Test {module

...方法

}

就能正常获取到 class Test 了。

研究了一下,发现缘由是 exports 的指向被重写了。

最初的时候,exports 是指向 module.exports 的,所以使用

exports.Test = Test;

这样也是能够从其它文件中获取到 Test 的:

 const Test = require("./example.js").Test;

这样便可。

可是若是写成

exports = {

Test

}

这样的话,在其它页面,使用

const exa = require("./example.js");

获取到的 exa 其实是 module.exports ,最初的 exports = module.exports = {} ,可是后来把 exports 指向其它对象以后, module.exports 并不会一样指向其它对象,也就是说 exports 是单向指向 module.exports 的,两者并不相等。所以,这里的 exa = {}, 而不是 exports 指向的对象。

另外,即便 exports 正确使用了

exports.Test = Test;

可是若是在后面又定义了

module.exports = {

...

};

也会使 module.exports 指向的对象再也不是最初的对象,致使 exports 的属性失效。

 

所以,一个比较好的实践是,在文件的最开头就定义好:

exports = module.exports;

强行把两个对象相等,这样,就能够直接写

exports = function() {

...

}

或者

exports = {

...

}

了。 

相关文章
相关标签/搜索