MST

星途 面试题库

面试题:Node.js 中 CommonJS 规范的模块导出方式有哪些区别

在 Node.js 的 CommonJS 规范下,有 `exports`、`module.exports` 两种常见的模块导出方式,请详细说明它们的区别以及在实际使用中需要注意的地方。
11.5万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

区别

  1. 本质区别
    • exportsmodule.exports 的一个引用。在 Node.js 的 CommonJS 模块系统中,每个模块都有一个 module 对象,module.exports 才是真正被导出的对象。exports 一开始指向 module.exports,即 exports === module.exports 在模块开始执行时为 true
    • 例如,在一个模块中:
console.log(exports === module.exports); // true
  1. 赋值操作区别
    • 如果对 exports 进行重新赋值(例如 exports = { newKey: 'newValue' };),那么 exports 将不再指向 module.exports,此时 exports 的修改不会影响到最终被导出的 module.exports
    • 而直接对 module.exports 进行赋值(例如 module.exports = { newKey: 'newValue' };),则会改变最终被导出的对象。
    • 示例代码如下:
// exports 重新赋值
exports.oldKey = 'oldValue';
exports = { newKey: 'newValue' };
// 这里导出的对象不会有 newKey 属性,因为重新赋值后 exports 不再指向 module.exports
module.exports.oldKey; // 'oldValue'
module.exports.newKey; // undefined

// module.exports 重新赋值
module.exports = { newKey: 'newValue' };
// 这里导出的对象有 newKey 属性
module.exports.newKey; // 'newValue'

实际使用注意点

  1. 推荐使用 module.exports:为了避免因 exports 重新赋值导致的导出错误,推荐直接使用 module.exports 进行模块导出。这样可以更清晰地控制导出对象,并且不容易出错。
  2. 使用 exports 时避免重新赋值:如果使用 exports,只在原对象基础上添加属性和方法,不要对 exports 进行重新赋值操作。例如:
exports.add = function(a, b) {
    return a + b;
};
  1. 混合使用注意:不建议在同一个模块中既对 exports 重新赋值,又对 module.exports 进行操作,这会使代码逻辑混乱,难以维护。如果一开始使用 exports 向对象添加属性和方法,就不要中途对 exports 重新赋值;如果需要完全替换导出对象,就直接使用 module.exports 进行赋值。