Analysis of the difference between exports and module.exports


In Node.js, we often encounter two keywords: exports and module.exports. They are used to export functions, objects, or variables in a module so that other modules can use them. Although they serve the same purpose, there are some subtle differences between them.

First, let's understand the respective roles of exports and module.exports.

exports is a reference to module.exports, which is an empty object. In a module, we can add properties and methods to the exports object and then export them to other modules through the require statement. This is a simplified export method provided by Node.js.

module.exports is the real export object. Its initial value is an empty object, but a function, object, or variable can be derived by direct assignment. When we export content using module.exports in a module, it will overwrite the reference of the exports object.

Below we use sample code to explain the difference between exports and module.exports in detail.

Sample code:

Let's say we have a module called math.js which contains some math functions.

// math.js

// 使用exports方式导出
exports.add = function(

Guess you like

Origin blog.csdn.net/Jack_user/article/details/133593343