Nodejs之什么是模块化

时间:2021-08-18 10:31:23   收藏:0   阅读:29

1. 什么是模块化

2. CommonJS 模块规范

在 Node 中的 JavaScript 还有一个很重要的概念:模块系统

- 模块作用域
- 使用 require 方法用来加载模块
- 使用 exports 接口对象用来导出模块中的成员

3. 加载 require

语法:

var 自定义变量名称=require(‘模块‘)

两个作用:

4. 导出 exports

 

 

5.原理解析

exports 和 module.exports 的引用

console.log(exports===module.exports)//=>true
?
exports.foo=‘bar‘
?
// 等价于
module.exports.foo=‘bar‘

exports 和 module.exports 的区别

  1. 每个模块中都有一个 module 对象

  2. module 对象中有一个 exports对象

  3. 我们可以把需要导出的成员都挂载到 module.exports 接口对象中

  4. 也就是:module.exports.xxx=xxx的方式,但是每次都module.exports.xxx=xxx很麻烦,点儿太多了

  5. 所以 Node 为了你方便。同时在每一个模块中都提供了一个成员叫:exports

  6. exports===module.exports 结果为true

  7. 当一个模块需要导出单个成员的时候,这个时候必须使用 module.exports=xxx 的方式

  8. 不要使用 exports=xxx不管用

  9. 因为每个模块最终向外return 的是 module.exports

  10. 而 exports只是 module.exports 的一个引用

  11. 所以即便你为 exports=xx 重新赋值,也不会影响 module.exports

  12. 但是有一种赋值方式比较特殊 exports=module.exports 这个用来重新建立引用关系的

 

require 方法加载规则

 

原文:https://www.cnblogs.com/SummerWithYou/p/15154629.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!