Home >Web Front-end >JS Tutorial >How Does Node.js's `module.exports` Work to Share Code Between Modules?

How Does Node.js's `module.exports` Work to Share Code Between Modules?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 03:50:09463browse

How Does Node.js's `module.exports` Work to Share Code Between Modules?

Understanding the Purpose and Usage of Node.js module.exports

Node.js modules are fundamental building blocks for organizing and sharing code. A crucial aspect of modular programming is the ability to expose specific functions or objects from a module for use in other parts of your application. This is where the module.exports variable comes into play.

module.exports is an object that acts as the return value of a require statement. It allows you to define and export specific elements from a module, making them accessible to other modules or the main application script.

In usage, you would typically define the functions or objects you want to export and assign them to exports, like:

// mymodule.js
let myFunc1 = () => { ... };
let myFunc2 = () => { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;

In the calling code, you can use require to load the module and access the exported functions:

// main.js
const m = require('./mymodule');
m.myFunc1();

m will hold the exported mymodule object, allowing you to invoke myFunc1 directly.

Note that exports is initially a reference to module.exports, so you can also assign to module.exports directly:

module.exports = {
  myFunc1,
  myFunc2,
};

Assigning a new value to exports will overwrite the reference to module.exports, so it's good practice to always assign to module.exports if you replace the exported object or function.

Finally, the names assigned to exported objects don't have to match their internal names in the module. For example:

module.exports = {
  shortAlias: myLongInternalName,
};

Allows you to use a different alias (shortAlias) when importing and using the function in the calling code:

const m = require('./mymodule');
m.shortAlias(); // Executes myLongInternalName

The above is the detailed content of How Does Node.js's `module.exports` Work to Share Code Between Modules?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn