一、加载模块
使用强大的require()方法,可以加在需要的内置模块,用户自定义模块,第三方模块进行使用,例如:
// 加载内置的fs模块
const fs = require('fs')
// 加载用户的自定义模块,一个js文件就相当于一个模块
const custom = require('./custom.js')
// 加载第三方模块
const moment = require('moment')
二、模块作用域
原因:防止了全局变量污染的问题。
在每个.js的自定义模块中都有一个module对象,它里面存储了和当前模块有关的信息。默认情况下,module.exports = {}。
在自定义模块中,可以使用module.exports对象,将模块内的成员共享出去,供外界使用。外界使用require()方法导入自定义模块时,得到的就是module.exports所指向的对象。
// 1、向 module.exports对象上挂载属性username
module.exports.username = 'zs'
// exports.username = 'zs'
// 2、向 module.exports对象上挂载方法sayHello
module.exports.sayHello = function() {
console.log('Hello~')
}
// 3、让 module.exports 指向一个全新的对象
module.exports = {
nickname: 'xiaohaung',
sayHi() {
console.log('Hi~')
}
}
console.log(module.exports === exports) // true
时刻谨记,require()模块时,得到的永远是module.exports指向的对象
三、CommonJS规定
- 每个模块内部,module变量代表当前模块;
- module变量是一个对象,它的exports属性是对外的接口;
- 加载某个模块,其实是加载该模块的module.exports属性。require()用于加载模块。