小知识:node.js里 exports 和 module.exports

这两者都是要暴露API,exports 是module.exports的一个引用,默认情况下就是一个对象:

exports:  通过形式如(exports.变量名)这种方式暴露的各种变量,最后都会归到一个未命名的对象之下,这个对象的命名则在要引入的模块中定义,代码如下

/**module_a.js*/
exports.name = 'jhon';
exports.data = 'there are some data';

var privateVal = 5;
exports.getVal = function () {
    return privateVal
}

/**index.js*/
var a = require('./module_a');
console.log(a.name);         //john
console.log(a.data);         // there are some data
console.log(a.getVal());     // 5

在module_a.js里exports出来的各种变量,函数,在引入index.js时候,统一归到自定义变量a下面,成为a的属性。

module.exports:  module.exports就不限定是一个对象了,可以是多个对象的集合

/**module_b.js*/
var data = 'there are some data';
var cg = function () {
    console.log(1);
};
var obj = {
    age:18,
    act:function () {
        console.log(haha);
    },
}

module.exports = {
    obj,data,cg
}

/**index_b.js*/
var b = require('./module_b');

console.log(b.data);  //there are some data
console.log(b.cg());  //  1
console.log(b.obj);   //{ age: 18, act: [Function: act] }

 

 

猜你喜欢

转载自blog.csdn.net/weixin_42273637/article/details/84429001