Nodejs 一句话说清exports和module.exports的区别

Nodejs 一句话说清exports和module.exports的区别

无需多言,不明白这两者区别的大多没看官方解释,只有一句话 If you want the root of your module’s export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.

大家明白了吧


8 回复

当然可以!以下是一个简洁的帖子内容,包含了你提到的要求,并附带了示例代码。


Nodejs 一句话说清 exportsmodule.exports 的区别

在 Node.js 中,exportsmodule.exports 都用于模块导出,但它们的工作方式有所不同。简而言之:

如果希望模块的根导出为一个函数(例如构造函数)或一次性导出一个完整的对象,而不是逐个属性地构建它,则应将该对象赋值给 module.exports 而不是 exports

// 示例1: 使用 exports 导出多个属性
// lib.js
exports.name = 'Alice';
exports.age = 30;

// 在其他文件中导入
const lib = require('./lib');
console.log(lib.name); // 输出: Alice
console.log(lib.age);  // 输出: 30

// 示例2: 使用 module.exports 导出一个完整对象
// lib.js
module.exports = {
    name: 'Bob',
    age: 25,
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

// 在其他文件中导入
const lib = require('./lib');
console.log(lib.name); // 输出: Bob
console.log(lib.age);  // 输出: 25
lib.greet();           // 输出: Hello, my name is Bob

通过这两个示例,你应该能清楚地理解 exportsmodule.exports 的区别了。


希望这能帮助你更好地理解 Node.js 中的模块导出机制。


//个人理解 //node.js 默认声明 //var exports = {}; //module.exports = exports;

moudle.exports = {a:1}; exports.a = 2;

//导出的是{a:1}

不难理解

很简单, exports是入参, 外部传入的是module.exports, 而修改入参的引用并不会影响外部对象

var module = {
  exports: {}
};

function your_module_define(require, exports, module){
 //修改入参的引用, 不会影响外部变量
 exports = {
   nouse: null
 };
 //修改对象的引用才有用
 module.exports = {}
}

其实懂引用类型和值类型的都会很容易理解吧。。

对于Node.js中的exportsmodule.exports,它们之间的区别可以用一句话来概括:

如果要将模块的根导出设置为一个函数(例如构造函数),或者一次性导出一个完整的对象,应该使用module.exports而不是exports

下面是简单的示例代码来说明这一点:

// 示例1: 使用exports
exports.sayHello = function() {
    console.log("Hello from exports!");
};

// 示例2: 使用module.exports
module.exports = {
    sayHello: function() {
        console.log("Hello from module.exports!");
    }
};

在这个例子中,如果你想要直接替换整个导出的对象,应该使用module.exports,如示例2所示。这样可以确保你的导出是一个全新的对象。

而如果你只是想添加或修改已有的导出,可以继续使用exports,如示例1所示。

回到顶部