持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情
模块化
- 内置模块
- 自定义模块
- 第三方模块 导入方式
//1.加载内置模块
const fs=require('fs')
//2. 记载自定义模块
const coust=require('./coust.JS')
//3.加载第三方模块
const moment=require('moment')
使用自定义模块时需要导入文件的位置
模块作用域
在模块内定义的成员无法被访问
module对象
外界使用require()导入的模块,实际上导入的是module.exports
写一个自定义模块,向别的文件挂载对象
//挂载username属性
module.exports.username='zs'
//挂载 方法
module.exports.sayHello=function(){
console.log('hello')
}
再另一个文件中打印出来为
{ username: 'zs', sayHello: [Function (anonymous)] }
module.exports的另一种写法
module.exports和export是等效的,使用export挂载的内容也能正常返回调用点
//挂载username属性
exports.username='zs'
//挂载 方法
exports.sayHello=function(){
console.log('hello')
}
共享成员注意点
使用require()方法导入模块时,导入的结果,永远以module.exports指向的对象为准
//挂载username属性
module.exports.username='zs'
//挂载 方法
module.exports.sayHello=function(){
console.log('hello')
}
module.exports={
rickname:'小王',
sayHi(){
console.log('Hi')
}
}
再另一个文件中打印出来为
{ rickname: '小王', sayHi: [Function: sayHi] }
结果 : 使用module.exports 方法挂载的变量 会被最后一个对象代替
使用误区
module.exports 与export 指向的对象如果不一样 结果会返回module.exports指向的对象(注意是指向的对象而不是指向的内容 如果先使用export指向一个对象那么module.exporsts也会指向该对象,后续通过module.exporsts指向的内容也会到这个对象中去)
为了防止混乱,在一个模块中不要同时使用module.exports 与export
模块化规范
Node.js遵循了ComminJS模块化规范,CommonJS规定了模块的特性和各模块之间如何相互依赖 CommonJS规范
- 每个模块内部,module变量代表当前模块
- module变量是一个对象,他的exports属性是对外的接口
- 加载某个模块,其实是记载该模块的module.exports属性。(require()方法用于加载模块)