module.exports 和 exports的区别
引用传递的理解 就理解了这两者的区别
var arr = [10,20,30];
var newarr = arr;
console.log(arr);//[10,20,30]
console.log(newarr);//[10,20,30];
newarr[0] = 40;
console.log(arr);//[40,20,30];
console.log(newarr);//[40,20,30];
例一. 采用module.exports
module.exports = {
hello: "hello",
world: "world"
};
例二. 采用exports
exports.hello = "hello"; exports.world= "world";
区别
exports = {
hello: "hello",
world: "world"
};//这样代码不报错, 但是没有用, 接口并未暴露出来. 原因请看下面
var load = function (exports, module) {
// .js的文件内容
...
// load函数返回:
return module.exports;
};
var exported = load(module.exports, module);
系统自动给nodejs 文件增加2个变量 exports 和 module, module 又有一个属性 exports, 这个exports 属性指向一个空对象 {}; 同时 exports这个变量也指向了这个空对象{};
于是就有了 exports => {} <=module.exports.
就是说自己定义一个exports没有用的,必须给modul。exports设置key:value值(exports.text= "hello")才可以,因为最后是导出 module.exports。
(外加:node.js是遵循common.js 实用const ** = require("**") 和 module.exports暴露模块,而浏览器v8引擎是解析js脚本文件的,并不能运行node.js的模块。)
推荐用module.exports导出。

浙公网安备 33010602011771号