CommonJS规范中module.exports和exports的区别

本文深入解析Node.js中module.exports与exports的区别及使用场景,通过实例对比,讲解如何正确导出模块对象,避免常见误区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚开始接触nodejs的同学对module.exports和exports的使用会有困惑,到底该使用哪一个,还是两个都可以使用,要理解二者的区别,应该先理解nodejs中require的加载机制。

// 准备module对象:
var module = {
    id: 'hello',
    exports: {}
};
var load = function (module,exports) {
    // 下面是加载的js代码:
    let foo='hello';
    module.exports = foo;
    // 最后返回module.exports
    return module.exports;
};
var exported = load(module,module.exports);
// 保存module:
save(module, exported);

 从中可以看出一个模块被引用的时候最终都会被输出成module.exports,而exports只是module.exports的一个引用,说到这里大家应该明白二者区别了。

下面例子

let name = "张三";
let age = 18;
let sayhello = () => {
    console.log(name);
}
exports.name=name;
exports.age=age;
exports.sayhello=sayhello;

 等价于

let name = "张三";
let age = 18;
let sayhello = () => {
    console.log(name);
}
module.exports.name=name;
module.exports.age=age;
module.exports.sayhello=sayhello;

  等价于

let name = "张三";
let age = 18;
let sayhello = () => {
    console.log(name);
}
module.exports={name,age,sayhello};

但是不能这样写,如果对exports对象重新赋值,那么最终module.exports的值将是空对象。

let name = "张三";
let age = 18;
let sayhello = () => {
    console.log(name);
}
exports={name,age,sayhello};

 总结:如果导出的不是对象,使用module.exports和exports没有区别,如果导出的是对象只能使用module.exports

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值