当前位置: 代码迷 >> 综合 >> nodejs exports 和 module.exports 的区别
  详细解决方案

nodejs exports 和 module.exports 的区别

热度:55   发布时间:2023-12-16 18:27:19.0

这应该是基础的内容了, 但是写 vue 写多了(ES6),慢慢的..我居然老想用ES6的语法来写nodejs(CommonJS)...,记录一下

首先做个实现就知道是怎么回事了

1.就写这一行代码,运行查看结果

console.log(module);
7942449-c7006eecd50c68f2.png
运行结果
{id: '.',exports: {},parent: null,filename: 'C:\\Users\\Administrator\\Desktop\\study\\index.js',loaded: false,children: [],paths: ['C:\\Users\\Administrator\\Desktop\\study\\node_modules','C:\\Users\\Administrator\\Desktop\\node_modules','C:\\Users\\Administrator\\node_modules','C:\\Users\\node_modules','C:\\node_modules']
}
  1. 我们可以会得到这样一个对象, 那么 module 是哪里来的?
    在 nodejs 中, 一个模块就是一个闭包, 大概是这样一个结构, 所以我们不需要定义就可以直接使用 modeulexports
(function (module, exports) {// code
})();

区别

console.log(module) 运行结果的代码中,可以看到 exportsmodule 的一个属性

  1. 如果使用 module.exports = {} 这是将系统的 exports 重新赋值了
module.exports = {name: 'jack',message: 'hello world'
};
  1. 如果使用 exports.aaa = 'bbb' 这是将 bbb 赋值给 exportsaaa 属性
exports.fun1= () => {console.log("hello");
}exports.fun2= () => {console.log("world");
}
  相关解决方案