JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Modules

14 April 2025 | Category:

JavaScript Modules allow you to split your code into separate files, making it easier to manage, maintain, and reuse code. Modules were officially introduced in ES6 (ECMAScript 2015) and are now a core part of writing clean, scalable JavaScript applications.


🔍 What Are Modules?

A module is a JavaScript file that exports variables, functions, classes, or objects so that they can be imported and used in other JavaScript files.


🎯 Why Use Modules?

  • Code Reusability: Use the same function or component in multiple files.
  • Maintainability: Keep related logic in dedicated files.
  • Namespace Isolation: Avoid polluting the global scope.
  • Scalability: Essential for large applications (like React, Vue, etc.).

đŸ§Ș Example: Creating and Using Modules

👉 math.js (Exporting module)

// Named exports
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// Default export
const multiply = (a, b) => a * b;
export default multiply;

👉 main.js (Importing module)

// Importing named exports
import { add, subtract } from './math.js';

// Importing default export
import multiply from './math.js';

console.log(add(5, 3));       // 8
console.log(subtract(5, 3));  // 2
console.log(multiply(5, 3));  // 15

Note: In Node.js or bundlers like Webpack, you’ll need to ensure the file is treated as a module using "type": "module" in package.json, or use .mjs extension.


đŸ“€ Exporting

1. Named Export

You can export multiple values using export in front of each item.

export const PI = 3.14;
export function greet(name) {
  return `Hello, ${name}!`;
}

Or group them together:

const PI = 3.14;
const greet = name => `Hello, ${name}`;
export { PI, greet };

2. Default Export

Each module can only have one default export:

export default function sayHi() {
  console.log("Hi!");
}

đŸ“„ Importing

1. Named Import

import { greet, PI } from './module.js';

2. Default Import

import sayHi from './module.js';

3. Renaming Imports

import { greet as sayHello } from './module.js';

🧠 Dynamic Imports

Modules can also be loaded dynamically using import() syntax (returns a promise).

async function loadModule() {
  const module = await import('./math.js');
  console.log(module.add(2, 3));
}
loadModule();

✅ Useful for code splitting and lazy loading in apps.


🌐 Modules in Browsers

In HTML:

<script type="module" src="main.js"></script>

✔ Modules are deferred by default
✔ import/export works only inside type="module" scripts


đŸ§± Modules in Node.js

In Node.js (v12+), to use ES modules:

  1. Set "type": "module" in package.json
  2. Use .js or .mjs files
{
  "type": "module"
}

OR

node --experimental-modules main.mjs

📌 Key Benefits

FeatureBenefit
import/exportOrganize code into small reusable units
Scope isolationAvoid global variable conflicts
Static structureEasier for bundlers and optimization
Dynamic importsLoad code only when needed

đŸš« Common Errors

  • Cannot use import statement outside a module: Make sure you use type="module" in HTML or configure your bundler properly.
  • SyntaxError: Unexpected token ‘export’: File is not treated as a module (e.g., in CommonJS environments).

🔚 Conclusion

JavaScript Modules bring structure and clarity to modern JavaScript development. Whether you’re building a small script or a large web application, using modules helps keep your code clean, maintainable, and scalable.