编程领域的模块化
编程领域的模块化就是遵守固定的规则,把一个大文件拆成独立并互相依赖的多个小模块。
模块化拆分代码的好处:
(1)提高了代码的复用性;
(2)提高了代码的可维护性;
(3)可以实现按需加载。
Node.js中的模块化分类
(1)内置模块:由 Node.js 官方提供的,例如 fs、path、http 等;
(2)自定义模块:用户创建的每个 .js 文件;
(3)第三方模块:由第三方开发出来的模块,使用前需要先下载。
加载模块
使用强大的 require() 方法,可以加载需要的模块进行使用:
// 加载内置模块,例如fs模块
const fs = require("fs");
// 加载用户自定义模块,这里可以省略 .js 的后缀名
const custom = require("./custom.js");
// 加载第三方模块
const moment = require("moment");
注意:使用 require() 方法加载其他模块时,会执行被加载模块中的代码。
模块作用域
与函数作用域类似,在自定义模块中的变量、方法等成员,只能在当前模块内被访问,这种模块化的访问限制叫做模块作用域。
模块作用域防止了全局变量污染的问题。
向外共享模块作用域中的成员
module对象
在每个 .js 自定义模块中都有一个 module 对象,它里面存储了和当前模块有关的信息,打印如下
module.exports 对象:
在自定义模块中,可以使用 module.exports 对象,将模块内的成员共享出去,供外界使用;
外界用 require() 方法导入自定义模块时,得到的就是 module.exports 所指定的对象;
默认情况下, module.exports 的值为 {}。
示例:
//test01.js
const m = require("./test01.1");
console.log(m);
//test01.1.js
const age = 20;
module.exports.username = "zs";
module.exports.sayHello = function () {
console.log("Hello");
};
module.exports.age = age;
使用 require() 方法导入模块时,导入的结果,永远以 module,exports 指向的对象为准:
示例:
//修改test01.1.js
const age = 20;
module.exports.username = "zs";
module.exports.sayHello = function () {
console.log("Hello");
};
module.exports.age = age;
module.exports = {
nickName: "小黑",
sayHi() {
console.log("Hi!");
},
};
export对象
由于 module.exports 单词拼起来比较复杂,为了简化向外共享成员的代码,Node 提供了 exports 对象。默认情况下,exports 和 module.exports 指向同一个对象。最终共享的结果,还是以 module.exports 指向的对象为准。
console.log(exports);
console.log(module.exports);
console.log(exports === module.exports);
exports 和 module.exports 的使用误区
时刻谨记,使用 require() 模块时,得到的永远是 module.exports 指向的对象
示例:
(1)
exports.userName = "zs";
module.exports = {
gender: "男",
age: 22,
};
//{ gender:'男', age:22 }
(2)
module.exports.userName = "zs";
exports = {
gender: "男",
age: 22,
};
//{ userName: 'zs' }
(3)
exports.userName = "zs";
module.exports.gender = "男";
//{ userName: 'zs', gender: '男' }
(4)
exports = {
userName: "zs",
gender: "男",
};
module.exports = exports;
module.exports.age = "22";
//{ userName: 'zs', gender: '男', age: '22' }
Node.js 中的模块化规范
Node.js 遵循了 CommonJS 模块化规范,CommonJS 规定了模块的特性和各模块之间如何互相转换;
CommonJS 规定:
(1)每个模块内部,module 变量代表当前模块;
(2)module 变量是一个对象,它的 exports 属性(即 module.exports) 是对外的接口;
(3)加载某个模块,其实就是加载该模块的 module.exports 属性。require() 方法用于加载模块。