Modules in JavaScript

Saugat GhimireSaugat Ghimire
2 min read

Modules can be defined as pieces of code that can be imported and exported between files. They help organize code by keeping it modular, maintainable, and easier to debug.

Types of Module

  1. ES Module ( ECMAScript Module - ESM)

    - Uses import and export keywords.

Let us have a file math.js

export function add(a,b){
return a+b;
}

Now for importing it over main.js

import { add } from './math.js';
console.log(add(2, 3));
  1. CommonJs Module ( CJS)

    - Uses require to import and module.exports to export.

Let us have a same file math.js (written over CJS)

function add(a,b){
return a+b;
}
module.exports={add};

main.js

const {add} = require("./math");
console.log(add(2,3));

Clearing Doubts 101

  1. Why do we use {add} and other time just add?

    Named exports

//named export ({ } needed)
export function add(a,b)
{
return a+b;
}

//importing in main.js
import {add} from './math.js';

Default Exports

 //Default export (no { } needed)
 export default function subtract(a,b)
 {
 return a-b;
 }

 //importing in main.js
 import add from './math.js';
  1. Bonus: in export default → no {} needed

    in named export → {} needed

  2. Sometime we import a file with ./math.js and other time just ./math. Why?

In ESM

import { add } from './math.js'; // Correct in ESM
import { add } from './math'; // Error in ESM

In Common Js

const math = require('./math'); // './math.js'
const math = require('./math.js'); // Works too

Importing a Directory

/math
  ├── index.js
  └── add.js

import { add } from './math';
0
Subscribe to my newsletter

Read articles from Saugat Ghimire directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saugat Ghimire
Saugat Ghimire