Node.js中exports、module.exports、require之间的关系

Node中的js文件

Node中的每个JS文件都是一个单独的模块,模块中包含的核心变量:exports、module.exports、require
nodejs中module文档
// 插入图片

Exports

初始值 exports = {};

The exports variable is available within a module’s file-level scope, and is assigned the value of module.exports before the module is evaluated.
// exports变量在模块的文件级范围内可用,并且在模块导出时赋值给module.exports
It allows a shortcut, so that module.exports.f = … can be written more succinctly as exports.f = …
// module.exports.f = … 允许使用简写的方式写为 exports.f = … (模块导出时默认采用 module.exports = exports)

exports.name = 'test';
exports.age = 111;
// 系统默认使用module.exports = exports导出
// 即 module.exports = exports = { name: 'test', age: 111, }

However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.exports:
// 然而需要注意的是像所有的变量一样,如果一个新值分配给exports,将不再绑定到module.exports上

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

Module.exports

The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to module.exports. Assigning the desired object to exports will simply rebind the local exports variable, which is probably not what is desired.
// module.exports 对象创建于模块系统,许多人希望他们的模块是自某些类的实例。由此将所需要导出的对象分配给module.exports; 将所需要的对象导出给exports只是简单的绑定到本地的exports变量,达不到想要的结果

module.exports = { ... } 
或
module.export = 基础类型

Require(id)

id module name or path
Returns: exported module content

Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, …/foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory. The relative paths of POSIX style are resolved in an OS independent fashion, meaning that the examples above will work on Windows in the same way they would on Unix systems
// 用于导入模块、JSON 和本地文件。可以从node_modules导入模块。本地模块和JSON文件可以使用相对路径(例如./,./foo,./bar/baz,…/foo)导入,该路径将根据__dirname命名的目录(如果已定义)或当前工作目录进行解析。POSIX 样式的相对路径以独立于操作系统的方式解析,这意味着上述示例将在 Windows 上以与在 Unix 系统上相同的方式工作。

Exports 、 module.exports 、 require之间的关系

在这里插入图片描述

  • 默认情况下 module.exports 引用exports对象; 自定义module.exports时跳过exports对象输出自定义内容
  • require引用module.exports导出的对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值