nodeJs的模块导出什么?

本文详细解析了Node.js中的module.exports和exports的区别,指出module.exports用于定义模块导出内容,而exports是一个对象,当module.exports被重新赋值时,会改变其地址,导致exports和module.exports指向不同。
摘要由CSDN通过智能技术生成

首先回答题目,nodeJs的模块导出什么?导出的是module.exports

在研究module前,我们先看看NodeJs官方解释

CommonJS 模块是为 Node.js 打包 JavaScript 代码的原始方式。 Node.js 还支持浏览器和其他 JavaScript 运行时使用的 ECMAScript 模块 标准。在 Node.js 中,每个文件都被视为一个单独的模块。

A reference to the current module, see the section about the module object. In particular, module.exports is used for defining what a module exports and makes available through require().

module 对象是当前模块对象的引用,module.exports是有 Module 系统创建的,用来表示将从该模块中导出的内容

这有一道经典题目关于exports,module.export,先看官方给的说明

It allows a shortcut, so that module.exports.f = … can be written more succinctly as exports.f = … However, be aware that like any variable, if a new value is assigned to
它允许一个捷径,使 module.exports.f = ... 可以更简洁地写成 exports.f = ...。 但是,请注意,与任何变量一样,如果将新值分配给 exports,则它不再绑定到 module.exports

module.exports.hello = true; // Exported from require of module
exports = { hello: false };  // Not exported, only available in the module

正常情况下我们在node环境下建立一个js文件直接打印

console.log(exports, module.exports, exports === module.exports);
//            {}           {}                 true    

下面呢?

exports.a = 2;
module.exports.a = 3;
console.log(exports, module.exports, exports === module.exports);
//           {a: 3}       {a: 3}              true

再下面呢?

  exports.a = 2;
  module.exports = { b: 3 };
  console.log(exports, module.exports, exports === module.exports);
  //           {a: 2}      {b: 3}              false

为什么这样?exports其实是个对象,module.exports == exports
加入在打印的是地址module.export=4643FH…那么exorts地址和他一样,当我们 module.exports = { b: 3 };相当于更换地址,module.export ==9752243FH…两个地址就不一样,而我们require的是module.exports,不是exports

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值