2.Node.js中的模块化

Node.js 中模块的分类

  • 内置模块 内置模块是由 Node.js 官方提供的,例如 fs、path、http 等
  • 自定义模块 用户创建的每个 .js 文件,都是自定义模块
  • **第三方模块 **

加载模块

  • **require() 方法 ** 按需加载内置模块、自定义模块、第三方模块
const fs=require("fs");

// 自定义模块 需要给出路径  可以补全 .js 后缀名(可以省略 .js后缀名)
const custom=require("./costum.js");

const moment=require('moment')  // 第三方 直接写名字

注意:使用 require() 方法加载其它模块时,会执行被加载模块中的代码

模块作用域

在自定义模块中定义的变量、方法等成员,只能在当前模块内被访问 防止了全局变量污染的问题

module对象

在每个 .js 自定义模块中都有一个 module 对象,它里面存储了和当前模块有关的信息

modeule.exports 对象

使用 module.exports 对象,暴露模块

***外界用 require() 方法导入自定义模块时,得到的就是 module.exports 所指向的对象 默认情况下 module.exports 为空对象 ***

// 在一个自定义模块中,默认情况下, module.exports = {}
const age=20;
module.exports.username="zs";
module.exoprts.sayHello=function(){
     console.log("HEllo");
}
modeule.exports.age=age;

// 另一个文件
const m=require("./xxxxxx")
console.log(m);

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UkhzydwI-1650368531866)(C:\Users\1301338853\AppData\Roaming\Typora\typora-user-images\image-20220418184940615.png)]

使用 require() 方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准

const age = 20
module.exports.username = 'zs'
module.exports.sayHello = function() {
  console.log('Hello!')
}
module.exports.age = age

// 让 module.exports 指向一个全新的对象
module.exports = {
  nickname: '小黑',
  sayHi() {
    console.log('Hi!')
  }
}


const m = require('./11.自定义模块') 
console.log(m)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7O5cqo9U-1650368531868)(C:\Users\1301338853\AppData\Roaming\Typora\typora-user-images\image-20220418190100324.png)]

exports 对象

默认情况下,exportsmodul.exports 指向同一个对象。最终共享的结果,还是以 module.exports 指向的对象为准

console.log(exports===module.exports);  // true

module.exports = {
  nickname: "小黑",
  sayHi() {
    console.log("Hi!");
  },
};

const age = 20;
exports.username = "zs";
exports.sayHi = function () {
  console.log("zzz");
};
exports.age = age;


const m = require('./13.exports对象')
console.log(m)
//最终共享的结果,还是以 **module.exports 指向的对象为准

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zecWmIsl-1650368531869)(C:\Users\1301338853\AppData\Roaming\Typora\typora-user-images\image-20220418191132900.png)]

Node.js 中的模块化规范

Node.js 遵循了CommonJS 模块化规范,规定了模块特性和各模块之间如何相互依赖

CommonJS规定:

  1. 每个模块内部 ,module 变量代表当前模块
  2. module 变量是一个对象,他的export 属性(module.exports)是对外的接口
  3. 加载( require() 方法 )某个模块,其实是加载该模块的 module.exports 属性
    代表当前模块**
  4. module 变量是一个对象,他的export 属性(module.exports)是对外的接口
  5. 加载( require() 方法 )某个模块,其实是加载该模块的 module.exports 属性
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值