exports 与 module.exports

exports 和 module.exports 的区别

很多新手可能会迷惑于 exports 和 module.exports 的区别,下面我来说一下两者的区别

exports 和 module.exports 都指向同一个空对象

1
2
3
console.log(module.exports);
console.log(exports);
console.log(module.exports===exports);

代码输出结果如下图
Alt text

exports 导出一个function

1
2
3
4
5
6
7
8
9
//test.js
exports.name = function() {
console.log('My name is sniperyan');
};
//index.js
var rocker = require('./test.js');
rocker.name(); //My name is sniperyan
import rocker from './test'
rocker.name(); //My name is sniperyan

我这是用babel编译的es6的写法,export导出name方法,require和import导入都可以执行

module.exports 导出一个function

1
2
3
4
5
6
7
8
9
//test.js
module.exports.name = function() {
console.log('My name is sniperyan');
};
//index.js
var rocker = require('./test.js');
rocker.name(); //My name is sniperyan
import rocker from './test'
rocker.name(); //My name is sniperyan

module.exports导出的方法,require和import导入都可以执行

Module.exports是真正的接口,exports只不过是它的一个辅助工具

1
2
3
4
5
6
7
8
9
10
11
//test.js
module.exports = function () {
console.log('module console');
};
exports.name = function() {
console.log('My name is sniperyan');
};
//index.js
var rocker = require('./test.js');
//import rocker from './test'
rocker.name();

这段代码中index.js报错,rocker.name is not a function , 这说明rocker模块忽略了exports收集的name方法,最终返回给调用的是Module.exports而不是exports,但是如果module.exports和exports都指向同一个变量,那最终的结果就如js中的对象引用同理。

你的模块可以是任何你设置给它的东西。如果你没有显式的给Module.exports设置任何属性和方法,那么你的模块就是exports设置给Module.exports的属性

1
2
3
4
5
6
7
8
9
10
11
12
//test.js
module.exports = function(name, age) {
this.name = name;
this.age = age;
this.about = function() {
console.log(this.name +' is '+ this.age +' years old');
};
};
//index.js
var rocker = require('./test.js');
var r = new rocker('Ozzy', 62);
r.about(); // Ozzy is 62 years old

如上代码,index.js中使用require方法,因为在模块导出的时候,没有显示的给模块设置任何的属性,如果使用export方法,将会报错,这也就解释了在react-router配置按需加载的时候,container导出的时候需要使用 module.exports而不用 export ,因为配置按需加载的语法使用的是require()引入

没有显式的给Module.exports设置任何属性和方法,你也可以使用import方法导入

1
2
3
4
5
6
7
8
9
10
11
12
//test.js
module.exports = function(name, age) {
this.name = name;
this.age = age;
this.about = function() {
console.log(this.name +' is '+ this.age +' years old');
};
};
//index.js
import rocker from './test'
var r = new rocker('Ozzy', 62);
r.about(); // Ozzy is 62 years old

总结

你的模块并不一定非得返回“实例化对象”。你的模块可以是任何合法的javascript对象–boolean, number, date, JSON, string, function, array等等。如果你想你的模块是一个特定的类型就用Module.exports。如果你想的模块是一个典型的“实例化对象”就用exports。前面已经提到module.exports是真正的接口,exports只不过是它的辅助工具。推荐使用exports导出。

请我吃辣条~~