JavaScript Modules (original) (raw)

Last Updated : 19 Feb, 2025

In JavaScript, modules are a fundamental feature for organizing, structuring, and reusing code. A module is simply a chunk of code that can be reused in different parts of a program or even in different programs. JavaScript’s modularity is key to managing complexity, especially for large applications.

What are modules in JavaScript?

A JavaScript module is a small piece of code that can be used in different parts of your program. It helps break down big projects into smaller, more manageable sections, each focused on a specific task. This makes your code easier to understand, maintain, and fix when needed. By using modules, you can keep your code organized and reuse parts of it across different projects.

**Modules can contain

Types of Modules

JavaScript provides two primary module systems

1. CommonJS Modules

In JavaScript, CommonJS is a module system primarily used in NodeJS environments. It enables developers to break down their code into reusable modules by using module.exports to export functions, objects, or variables from a module. Other modules can then access these exports using the require() function.

**Syntax

//import const module1 = require('./module1');

//export module.exports = { module1, module2, ....};

Working of CommonJS

Use cases of CommonJS module

**1. Creating a Utility Module

A Utility Module is a collection of reusable helper functions that make coding easier by handling common tasks like formatting, validation, and logging.

JavaScript ``

//one.js function greet(name) { return Hello, ${name}!; } module.exports = greet;

`` JavaScript `

// two.js const greet = require('./one.js'); console.log(greet('Sandeep'));

`

**Output

Screenshot-2025-02-19-123653

Creating a Utility Module

**2. Building a Configuration File

A Configuration File stores settings and environment-specific variables to manage an application's behavior. It helps keep code clean and flexible by separating configuration details from the main logic.

JavaScript `

//one.js module.exports = { port: 3000, dbURL: 'mongodb://localhost:27017/mydb' };

JavaScript

//two.js const config = require('./one.js'); console.log(config.port);

`

**Output

Screenshot-2025-02-19-164946

Building a Configuration File

**3. Handling Routes in an ExpressJS App

In an ExpressJS app, routes define how the application responds to client requests. They help organize API endpoints and handle different HTTP methods like GET, POST, PUT, and DELETE.

JavaScript `

// one.js const express = require('express'); const router = express.Router(); router.get('/', (req, res) => res.send('Home Page')); module.exports = router;

JavaScript

// two.js const express = require('express'); const app = express(); const routes = require('./one'); app.use('/', routes); app.listen(3000, () => console.log('Server running on port 3000'));

`

**Output

Screenshot-2025-02-19-130050

Handling Routes in an Express.js App

2. ES6 module

ES6 Modules (ECMAScript Modules) provide a standardized way to structure and organize JavaScript code into separate, reusable modules. Unlike CommonJS, ES6 Modules use the import and export keywords for handling exports and imports.

In JavaScript, setting "type": "module" in your package.json tells NodeJS to treat .js files as ES6 modules, enabling import and export syntax. With ES6 modules, NodeJS expects static import and export statements, which are optimized at compile time, leading to smaller bundles. This setup improves compatibility with modern JavaScript tools.

Working of ES6 modules

Screenshot-2025-01-25-083730

Here is the syntax for creating and using JavaScript modules. The example illustrates how to export and import functionality between files.

JavaScript `

//maths.js export function add(a,b){ return a+b } export const PI=3.1414

` JavaScript ``

//usess.js import {add,PI} from './maths.js' console.log(add(2,3)) console.log(The value of the PI is ${PI})

``

**Output

Screenshot-2025-01-25-083341

Use cases of ES6 modules

**1. Default Export and Import

This code showcases how to use JavaScript modules to define and import a function across different files. The greet function is defined in one file and used in another to demonstrate modularity.

JavaScript ``

//greet.js export default function greet(name) { return Hello, ${name}!; }

`` JavaScript `

// file: main.js import greet from './greet.js'; console.log(greet('GFG'));

`

**Output

Screenshot-2025-01-25-084043

Default Export and Import

**2. Named Exports with Aliases

This code demonstrates how to export multiple functions from a module and import them with new names for use in another file. It shows how to perform basic arithmetic operations using modular JavaScript.

JavaScript `

//Operations.js export function multiply(a, b) { return a * b; } export function divide(a, b) { return a / b; }

JavaScript

import { multiply as mul, divide as div } from './Operations.js'; console.log(mul(6, 3)); console.log(div(10, 2));

`

**Output

Screenshot-2025-02-19-145005

Named Exports with Aliases

**3. Dynamic Imports

This code demonstrates the use of dynamic import() in JavaScript to load a module asynchronously at runtime. It shows how to use the import() function to load a module and access its exports.

JavaScript `

//codes2.js (async () => { const module = await import('./codes1.js'); console.log(module.greet('GFG')); })();

` JavaScript ``

//codes1.js export const greet = (name) => Hi, ${name}!;

``

Screenshot-2025-01-25-090149

Dynamic Imports

**4. Combining Default and Named Exports

This code demonstrates how to export a default class and named functions from a module and import them in another file. It shows how to create an instance of a class and use both default and named.

JavaScript ``

//person.js export default class Person { constructor(name) { this.name = name; } sayHello() { return Hello, I am ${this.name}; } }

export const greet = (name) => Hi, ${name}!;

`` JavaScript `

import Person, { greet } from './person.js'; const aman = new Person('Aman'); console.log(aman.sayHello()); console.log(greet('Rohan'));

`

Screenshot-2025-01-25-090851

Combining Default and Named Exports

Key Features of JavaScript Modules

Why to use modules in JavaScript

Using modules provides several benefits, including