Mastering Modules in Node.js

Mastering Modules in Node.js

What is a Module?

A module is a piece of code that we can reuse or borrow from others and include in our own program.


Types of Modules in Node.js

There are two main ways to import and export modules in Node.js:

  1. CommonJS – This is the default and older system.
  2. ES Modules (also called ModuleJS) – This is the modern way, based on JavaScript's import/export syntax.

Key Differences Between CommonJS and ES Modules

  • CommonJS modules are loaded synchronously (one at a time, blocking the program until loaded).
  • ES Modules are loaded asynchronously (non-blocking, better for performance in some cases).

Code

CommonJS (Default in Node.js)

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 (also called ModuleJS)

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

⚠️ Note:

"type": "module" in package.json is needed to use the import/export syntax of ModuleJS in Node.js.


Conclusion

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!

Built with love by Ajay Panigrahi