A module is a piece of code that we can reuse or borrow from others and include in our own program.
There are two main ways to import and export modules in Node.js:
import/export
syntax.CommonJS uses module.exports to make values available and require() to bring them into other files.
module.exports = "Ajay"; // CommonJS export // default return => {}
const someModule = require("./index"); // CommonJS import
ES Modules use export to define what's available and import to use it. They offer more flexibility, allowing named exports to share multiple specific items like functions or variables by their exact names. A module can also have a single default export, which is the primary item it provides, and you can name it anything you want when importing.
export const firstName = "Ajay"; // Named export
import { firstName } from "./index.js"; // Named import
const firstName = "Ajay";
export default firstName; // Default export
import firstName from "./index.js"; // Default import
import youCanWriteAnyName from "./index.js"; // You can give any name while importing default export
"type": "module" in package.json is needed to use the import/export
syntax of ModuleJS in Node.js.
Understanding Node.js modules is fundamental to building any application. While CommonJS remains the default and is prevalent in existing codebases, ES Modules represent the future of JavaScript and offer modern syntax and asynchronous loading benefits. Knowing when and how to use both will make you a more versatile Node.js developer.
Start experimenting with both module types in your next Node.js project!