区别
- 本质:
exports
实际上是 module.exports
的一个引用。在Node.js模块的顶层作用域中,Node.js会自动创建一个 exports
对象,这个对象指向 module.exports
。
module.exports
是Node.js内部用于定义模块导出内容的核心对象。
- 赋值操作:
- 如果对
exports
进行重新赋值(例如 exports = { newProperty: 'newValue' }
),这并不会影响 module.exports
。因为此时 exports
指向了一个新的对象,不再与 module.exports
有引用关系。
- 对
module.exports
进行赋值(例如 module.exports = { newProperty: 'newValue' }
),则会改变模块实际导出的内容,因为模块最终导出的就是 module.exports
指向的对象。
场景举例
- 使用
exports
导出单个属性或方法:
- 当你只想为模块导出一些简单的属性或方法时,可以直接使用
exports
。例如,创建一个名为 mathUtils.js
的模块,用于导出一个简单的加法函数:
// mathUtils.js
exports.add = function(a, b) {
return a + b;
};
const mathUtils = require('./mathUtils');
console.log(mathUtils.add(2, 3));
- 使用
module.exports
导出复杂对象或构造函数:
- 当你需要导出一个复杂的对象,或者一个构造函数来创建实例时,更适合使用
module.exports
。例如,创建一个 Person
类的模块 person.js
:
// person.js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
};
module.exports = Person;
const Person = require('./person');
const john = new Person('John', 30);
john.sayHello();
// config.js
module.exports = {
database: {
host: 'localhost',
port: 3306,
user: 'root',
password: 'password'
},
server: {
port: 8080,
hostname: '127.0.0.1'
}
};
const config = require('./config');
console.log(config.database.host);