模块化是指解决一个复杂问题时,自顶向下逐层把系统划分成若干模块的过程。对于整个系统来说,模块是可组合、分解和更换的单元。
编程领域中的模块化,就是遵守固定的规则,把一个大文件拆成独立并互相依赖的多个小模块。
把代码进行模块化拆分的好处:
① 提高了代码的复用性
② 提高了代码的可维护性
③ 可以实现按需加载
模块化规范就是对代码进行模块化的拆分与组合时,需要遵守的那些规则。
例如:
模块化规范的好处:大家都遵守同样的模块化规范写代码,降低了沟通的成本,极大方便了各个模块之间的相互调用,利人利己。
Node.js 中根据模块来源的不同,将模块分为了 3 大类,分别是:
使用强大的 require() 方法,可以加载需要的内置模块、用户自定义模块、第三方模块进行使用。例如:
注意:使用 require() 方法加载其它模块时,会执行被加载模块中的代码。
和函数作用域类似,在自定义模块中定义的变量、方法等成员,只能在当前模块内被访问,这种模块级别的访问限制,叫做模块作用域
防止了全局变量污染的问题
username打印的是:ls
在每个 .js 自定义模块中都有一个 module 对象,它里面存储了和当前模块有关的信息,打印如下:
在自定义模块中,可以使用 module.exports 对象,将模块内的成员共享出去,供外界使用。
外界用 require() 方法导入自定义模块时,得到的就是 module.exports 所指向的对象。
1 2 3 4 5 6 7 8 9 |
// 在一个自定义模块中,默认情况下, 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 |
1 2 3 4 |
// 在外界使用 require 导入一个自定义模块的时候,得到的成员, // 就是 那个模块中,通过 module.exports 指向的那个对象 const m = require('./11.自定义模块') console.log(m) |
使用 require() 方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// 在一个自定义模块中,默认情况下, 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 // 让 module.exports 指向一个全新的对象 module.exports = { nickname: '小黑', sayHi() { console.log('Hi!') } } |
1 2 3 4 |
// 在外界使用 require 导入一个自定义模块的时候,得到的成员, // 就是 那个模块中,通过 module.exports 指向的那个对象 const m = require('./11.自定义模块') console.log(m) |
由于 module.exports 单词写起来比较复杂,为了简化向外共享成员的代码,Node 提供了 exports 对象。默认情况下,exports 和 module.exports 指向同一个对象。最终共享的结果,还是以 module.exports 指向的对象为准。
1 2 3 4 5 6 7 8 9 10 |
// console.log(exports)//{} // console.log(module.exports)//{} // console.log(exports === module.exports)//true const username = 'zs' module.exports.username = username exports.age = 20 exports.sayHello = function() { console.log('大家好!') } // 最终,向外共享的结果,永远都是 module.exports 所指向的对象 |
1 2 |
const m = require('./13.exports对象') console.log(m) |
时刻谨记,require() 模块时,得到的永远是 module.exports 指向的对象:
注意:为了防止混乱,建议大家不要在同一个模块中同时使用 exports 和 module.exports
Node.js 遵循了 CommonJS 模块化规范,CommonJS 规定了模块的特性和各模块之间如何相互依赖。
CommonJS 规定:
① 每个模块内部,module 变量代表当前模块。
② module 变量是一个对象,它的 exports 属性(即 module.exports)是对外的接口。
③ 加载某个模块,其实是加载该模块的 module.exports 属性。require() 方法用于加载模块