Node.js - how to use module exports
In this article, we would like to show you how to use module exports in Node.js.
1. IntroductionÂ
In Node.js, modules are the blocks of encapsulated code, functionality that can be shared and reused across projects. They also helps to organize the code, leading to easier to understand, debug and maintain the application.
2. Module formats
There are a few different types of module formats:
- CommonJS - format used in Node.js. Uses
module.exports to export modules andrequirekeyword to import them. - ES Module (ESM) - uses
exportkeyword to export modules and animportkeyword to import them (as ES6 native module format). - Asynchronous Module Definition (AMD) -Â
- Universal Module Definition (UMD) -Â Â can be used both in the browser and in Node.js. This format is useful when a module has to be imported by many different module loaders.
- System.register -Â designed to support ES6 modules within ES5
Note:
In this article we use the default for Node.js - CommonJS format.
3. Create and export module
To create a module, simply create a new file with some reusable code and use modules.export to export the functionality.Â
In below example we create and export User class in separate users.js file.
// ONLINE-RUNNER:browser;
module.exports = class User {
constructor(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
display() {
console.log(`id: ${this.id}, name: ${this.name}, age: ${this.age}`);
}
}
Note:
Go to te following article to see full explanation of the example:Â Node.js - export class from module.
4. Import module
After creating and exporting a module, import it in the main project file (e.g index.js) using the require keyword.
const User = require('./user');
Now you are able to use its functionality.
Practical example:
const User = require('./user');
const user1 = new User(1, 'Tom', 23);
user1.display();
Output:
id: 1, name: Tom, age: 23
Related posts
-
Enable
export/importkeyword: -
Export data: