module.exports对象、exports对象向外共享模块作用域中的成员

538 阅读3分钟

module 对象

 

 module.exports 对象的作用

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

   1 // 记载模块.js

2 const mo = require('./被加载的模块')

4 console.log(mo) // {} 

1 // 被加载的模块.js
2 
3 // 当外界使用 require 导入一个自定义模块的时候,得到的成员,就是模块中,通过 module.exports 指向的那个对象
4 // console.log('我会被加载')
使用 module.exports 向外共享成员

sum.js

 1 const username = 'ifer';
 2 const sum = (a, b) => a + b;
 3 
 4 // 最佳实践,推荐写法
 5 module.exports = {
 6     username,
 7     sum
 8 };
 9 
10 /* // 往 module.exports 对象上挂载了一个属性是一个字符串
11 module.exports.username = username;
12 
13 // 往 module.exports 对象上挂载了一个属性是一个方法
14 module.exports.sum = (a, b) => a + b; */

index.js

 1 // require 得到的结果就是这个 sum.js 文件中 module.exports 所指向的对象
 2 // ./ 一定不能省略,因为 sum.js 是一个自定义模块
 3 const modSum = require('./sum');
 4 
 5 const res = modSum.sum(1, 3);
 6 console.log(res); // 4
 7 
 8 // 这个 username 和引入的 sum.js 中的 username 没有任何关系
 9 const username = 'elser';
10 
11 console.log(username); // elser
12 console.log(modSum.username); // ifer

终端命令

node index.js
共享成员时的注意点:使用 require() 方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准
1 // 加载模块.js
2 const mo = require('./被加载的模块.js')
3 
4 console.log(mo) // { username: '小黑', sayHi: [Function: sayHi] }
 1 // 被加载模块.js
 2 
 3 // 当外界使用 require 导入一个自定义模块的时候,得到的成员,就是模块中,通过 module.exports 指向的那个对象
 4 // console.log(module)
 5 
 6 // 向 module.exports 对象上挂载 username 属性
 7 module.exports.username = 'zs'
 8 
 9 // 向 module.exports 对象上挂载 sayHello 方法
10 module.exports.sayHello = function () {
11   console.log('Hellp')
12 }
13 
14 // 使用 module.exports 指向一个全新的对象
15 module.exports = {
16   username: '小黑',
17   sayHi() {
18     console.log('小黑')
19   }
20 }

exports 对象

exports 和 module.exports 指向同一个对象。最终共享的结果,还是以 module.exports 指向的对象为准

1 console.log(exports)
2 
3 console.log(module.exports)
4 
5 // 默认情况下,`exports` 和 `module.exports` 指向同一个对象
6 console.log(exports === module.exports) // true
1 // 将私有成员共享出去
2 exports.username = 'zs'
3 
4 // 直接挂载方法
5 exports.sayHello = function () {
6   console.log('Hellp')
7 }

exports 和 module.exports 的使用误区

  1. 时刻谨记,==require() 模块时,得到的永远是 module.exports 指向的对象\

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

 1 exports.username = 'Tom' // 不会被打印
 2 
 3 module.exports = {
 4   gender: '男',
 5   age: 22
 6 }
 7 
 8 module.exports.username = 'Tom'
 9 
10 // 不会被执行
11 exports = {
12   gender: '男',
13   age: 22
14 }
15 
16 
17 // 两个都会执行
18 module.exports.username = 'Tom'
19 
20 exports.gender = '男'
21 
22 // 三个都会打印
23 exports = {
24   gender: '男',
25   age: 22
26 }
27 
28 module.exports = exports
29 module.exports.username = 'Tom'

CommonJS 模块化规范

  1. Node.js 遵循了 CommonJS 模块化规范,CommonJS规定了模块的特性和各模块之间如何相互依赖
  2. CommonJS 规定:
    • 每个模块内部,module 变量代表当前模块
    • module 变量是一个对象,它的 exports 属性(即 module.exports)是对外的接口
    • 加载某个模块,其实是加载该模块的 module.exports 属性。require() 方法用于加载模块