require的基本使用,理解module.exports与exports

require

本文是讲关于如何在node中使用require。

一、历史渊源

require时代的模块

​ node编程中最重要的思想之一就是模块,而正是这个思想,让JavaScript的大规模工程成为可能。模块化编程在js界流行,也是基于此,随后在浏览器端,requirejs和seajs之类的工具包也出现了,可以说在对应规范下,require统治了ES6之前的所有模块化编程,即使现在,在ES6 module被完全实现之前,还是这样。node的module遵循CommonJS规范,requirejs遵循AMD,seajs遵循CMD,虽各有不同,但总之还是希望保持较为统一的代码风格,ES6之后可以使用import 导入export导出,但还是得看当前的node版本是否支持该功能。

名称规范用途
node requireCommonJSnode后端
requirejsAMDweb前端
seajsCMDweb前端

二、require的使用

首先所有的文件都运行在node环境中同一个目录。

1.导出单个函数

假设我们要制作一个模块,要导出一个函数

//a.js
function hello(){
    console.log('hi! I am a.js')
}
module.exports = hello  //导出的函数

当要应用这个模块的时候

//index.js
let hello = require("./a.js")
hello()  //调用模块中函数,运行结果: hi! I am a.js

这样就导出函数hello最终module.eports是一个作为被导出的对象,一个模块只有一个导出对象module.exports,那么如何导出多个函数呢?聪明的你可能已经想到了,可以把多个方法放在同一个对象中

2.导出多个函数

导出多个函数

//a.js
function hello1(){
    console.log('hi! I am a1.js')
}
function hello2(){
    console.log('hi! I am a2.js')
}

module.exports.hello1 = hello1
module.exports.hello2 = hello2

使用多个函数

let foo = require("./a") //.js可以被省略

foo.hello1()
foo.hello2()

$ node index.js
hi! I am a1.js
hi! I am a2.js

3.exports与module.exports

也许你也见过这种写法

//a.js
function hello(){
    console.log('hi! I am a.js')
}
exports = hello  //导出的函数

这样也可以,在一个node执行一个文件时,会给这个文件内生成一个 exportsmodule对象,而module又有一个exports属性。他们之间的关系如下图,都指向一块{}内存区域。

exports = module.exports = {};

在这里插入图片描述

但是最终被模块所采用的是module.exports

//a.js
function hello(){
    console.log('hi! I am a.js')
}

exports.hello = hello; 

exports = '指向其他内存区'; //这里把exports的指向指走

//index.js

var hello = require('/a.js');
hello() //结果为 hi! I am a.js

刚开始exports与module.exports指向同一内存,exports.hello改变使得module.export也发生改变,随后exports改变了指向对象,但最终模块读取的是module.exports指向的那块内存

参考资料:

https://blog.csdn.net/qq_28702545/article/details/54892562

https://segmentfault.com/a/1190000010426778

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值