DEV Community

Cover image for NodeJS Modules [Simple Explanation]
Salman Arefin
Salman Arefin

Posted on

NodeJS Modules [Simple Explanation]

What are modules?

Imagine you have an index.js file in your NodeJS project where you have used five functions. However, two of these functions might also be used in other files. So, instead of one file, you create three files in your project:

  • index.js
  • dependency1.js
  • dependency2.js

Here, each of these Javascript files is a module, and the way to export classes/functions and import them is basically the module system. A module system allows us to split and include code and import code written by us or other developers whenever required.

These modules are not just the Javascript files that exist in your project; they can also be any external package you have installed as a dependency in your project. Also, NodeJS has some built-in modules like http, fs, etc., which are available along with installation and can be imported without adding any external dependencies.

How can I export or import a module?

Two module systems are used in Node.

  1. CommonJS (CJS)
  2. ECMAScript Module (ESM)

You have read the kitchen-chef-waiter example in my previous blog; Similarly, if we compare modules with that, imagine CommonJS is an old big recipe book we needed to search and find a recipe, while ESM is a new aged digital app to see recipes.

CommonJS (CJS)

  • The older module system.
  • Modules are written in a simple format like:
// Export
module.exports = function SayHello() {
  console.log("Hello World!");
};

// Import
const GetHello = require("./hello-script.js");
SayHello(); // "Hello World!"
Enter fullscreen mode Exit fullscreen mode
  • Synchronous: Loads modules one after another.
  • Works only in Node.js (not directly in browsers).

ECMAScript Modules (ESM)

  • The modern module system.
  • Modules are now more structured:
// Export
export function SayHello() {
  console.log("Hello World!");
}

// Import
import { SayHello } from "./hello-script.js";
SayHello();
Enter fullscreen mode Exit fullscreen mode
  • Asynchronous: Loads multiple modules at the same time.
  • Works natively in browsers and Node.js.

Key Difference in syntax:
CJS: module.exports / require
ESM: export / import

How do I configure CJS or ESM in my project?

  • Open the package.json of your project.
  • Add:
{
  type: "module";
}
Enter fullscreen mode Exit fullscreen mode
  • This tells NodeJS to interpret .js as ESM. If we don't add this, NodeJS will interpret it as CommonJS by default.

Modules in Typescript:

Sometimes, you can use ECMAScript modules but an old package you have imported is written in CommonJS. To handle these cases, we sometimes make sure the output Javascript code generated from the Typescript file comes in the common format, even though we have written the Typescript files in ESM format.

For this, we add the compilerOptions in the tsconfig.json of our project:

"compilerOptions": {
  "module": "commonjs",
  "target": "es6"
}
Enter fullscreen mode Exit fullscreen mode

What happens then:
module: "commonjs": Outputs JavaScript using the CommonJS module system, which uses require and module.exports.
target: "es6": Ensures that the output JavaScript uses ES6 syntax and features like let, const, and arrow functions.

Input Typescript code:

import { readFile } from "fs";

const SayHello = () => {
  console.log("Hello World!");
};

export { SayHello };
Enter fullscreen mode Exit fullscreen mode

Output Javascript code:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SayHello = void 0;
const fs_1 = require("fs");
const SayHello = () => {
    console.log("Hello World!");
};
exports.SayHello = SayHello;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
philip_zhang_854092d88473 profile image
Philip

Modules in Node.js help organize and reuse code by splitting it into separate files, using CommonJS or ECMAScript Modules for exporting and importing. Recently, i figured out EchoAPI which can assist by streamlining API testing and integration within modular projects, improving development speed and accuracy.