Node模块化

161 阅读3分钟

Node模块化

模块化的概念

编程领域中的模块化,就是遵守固定的规则,把一个大文件拆成独立并相互依赖的多个模块

把代码拆分的好处:

  1. 提高了代码的复用性
  2. 提高了代码的可维护性
  3. 可以实现按需加载

模块化规范

image.png

Node.js中模块化分类

image.png

image.png

指定义模块加载

在文件夹中指定义一个指定义模块

使用require()加载内置模块和指定义模块,指定义模块要写文件的路径 image.png

image.png

image.png

注意:在使用require加载用户指定义模块期间可以省略.js的后缀名

image.png

模块作用域

函数作用域类似,在自定义模块中定义的变量方法等成员,只能在当前模块内被访问,这种模块级别的访问限制就叫做模块作用域

image.png

我们可以导入自定义模块,但我们custom无法访问到自定义模块里面的内容所有我们打印出的就是{}空对象

模块作用域的好处:防止了全局变量污染问题。

module对象

在每一个.js自定义模块中都有一个module对象,它里面存储了和当前模块有关的信息,其中exports为{}空对象。 image.png

module.exports对象的作用

在自定义模块中,可以使用module.exports对象,将模块内的成员共享出去,供外界使用。外界用require()方法导入自定义模块时,得到的就是module.exports所指向的对象。

image.png

09-自定义模块.js

//自定义模块中,默认情况下,module.exports = {}
const age = 20
//向module.exports对象上挂载username属性
module.exports.username = 'zs'
//向module.exports对象上挂载sayHello方法
module.exports.sayHello = function () {
    console.log('Hello!');
}
module.exports.age = age

test

//在外界使用require导入一个自定义模块的时候,
// 得到的成员就是那个模块中,通过module.exports指向的那个对象
const m = require('./09-自定义模块.js')
console.log(m)

image.png

共享成员时的注意点

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

image.png

exports对象

由于module.export单词写起来比较复杂,为了简化向外共享成员的代码,Node提供了exports对象。默认情况下,export和module.exports指向同一个对象。最终共享的结果,还是以module.exports指向的对象为准.

console.log(exports)
console.log(module.exports);
console.log(exports === module.exports);
//1.定义模块私有成员 username
const username = 'zs'       //2.将私有成员共享出去
exports.username = username //3.直接挂载新的成员
exports.age = 20            //4.直接挂载方法
exports.sayHello = function () {
    console.log('大家好!');
}


//在外界使用require导入一个自定义模块的时候,
// 得到的成员就是那个模块中,通过module.exports指向的那个对象
const m = require('./09-自定义模块.js')
console.log(m)
const m1 = require('./11.export是否指向同一个module.export.js')
console.log(m1)

image.png

exports和module.exports的使用误区

require()永远指向module.exports对象{}

误区一: image.png

误区二: image.png

误区三:

image.png

误区四:

image.png

image.png

注意: 为了防止混乱,建议大家不要在同一个模块中同时使用exports和module.exports

Node.js中的模块化规范

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

CommonJS规定: 每个模块内部,module变量代表当前模块 module变量是一个对象,它的exports属性(module.exports)是对外的接口。 加载某个模块,其实是加载该模块的module.exports属性。require()方法用于加载模块。