node的模块导出与ES6的模块导出类似,node的模块导出是用exports和module.exports。
exports : 导出一个变量
module.exports : 导出一个json
引入则是用 require关键字
例子 :
config.js (需要被导出的数据存放在一个叫config.js的文件)
exports.a = [1,2,3,4,5];
exports.b = 2020;
server.js (我们再server.js中引入config.js的两个变量)
var config = require('./config.js');
console.log(config);
输出 :
{ a: [ 1, 2, 3, 4, 5 ], b: 2020 }
输出结果是一个json,它会把config.js中被exports修饰的变量都导出来。如果不想要json格式,则需要这样导入 :
var {a,b} = require('./app/config.js');
console.log(a);
console.log(b);
我们指定了导出a和b这两个变量。输出 :
[ 1, 2, 3, 4, 5 ]
2020
而module.exports的使用方法是一样的,一般来说它适用于导出一个json。例子 :
config.js
module.exports = {
a : 1,
b : 2,
c : 3
}
server.js
var config = require('./config.js');
console.log(config);
输出 :
{ a: 1, b: 2, c: 3 }