import and export 🎯Welcome to this comprehensive guide on ES Modules in Node.js! This tutorial is designed to help both beginners and intermediates understand the powerful features of importing and exporting modules, making your Node.js applications more modular, manageable, and efficient.
ES Modules (also known as ECMAScript modules) are a part of the JavaScript standard, allowing developers to create reusable and self-contained code snippets. They are a significant improvement over CommonJS, as they address issues like implicit globals and circular dependencies.
import and export 💡Importing a module in Node.js is as easy as using the import keyword followed by the module name.
// Importing a module named 'myModule'
import { someFunction } from 'myModule';You can import the entire module if it's a CommonJS module (i.e., .js or .json files) by using the require() function.
// Importing the entire 'myModule'
const myModule = require('./myModule');To make a module reusable, you need to export functions, classes, or variables using the export keyword.
// myModule.js
// Exporting a function
export function someFunction() {
// Your code here
}You can also export multiple functions, classes, or variables from a single file.
// myModule.js
// Exporting multiple functions
export function function1() {
// Your code here
}
export function function2() {
// Your code here
}When a module has a default export, you can import it using the import keyword without curly braces.
// myModule.js
// Default export
export default function defaultFunction() {
// Your code here
}
// In another file
import defaultFunction from 'myModule';node_modules 📝Node.js uses a specific set of rules to locate and load the requested module. This process is called module resolution. When you import a module, Node.js looks for it in the following order:
node_modules directory of the current projectnode_modulesWhen importing a third-party module, it's usually located within the node_modules directory.
ES Modules and CommonJS have their differences. While CommonJS uses require() and exports via object, ES Modules use the import and export syntax. To use ES Modules in Node.js, you need to enable the feature using the --experimental-modules flag.
node --experimental-modules yourScript.mjsimport { someFunction1, someFunction2 } from 'myModule1';
import { anotherFunction } from 'myModule2';// myModule.js
export function function1() {
// Your code here
}
export function function2() {
// Your code here
}// myModule.js
export default function defaultFunction() {
// Your code here
}// Importing and using the default export
import defaultFunction from 'myModule';
defaultFunction();What is the purpose of the `import` keyword in Node.js?
What is the difference between CommonJS and ES Modules in Node.js?