DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 22: Modules

As projects grow in complexity, organising code becomes crucial for maintainability and collaboration. That's where JavaScript modules come into play.

📦 What are JavaScript Modules?

JavaScript modules are self-contained units of code that encapsulate functionality. They allow developers to split their codebase into separate files, each containing related functionality. By doing so, modules help avoid polluting the global scope, reduce naming conflicts, and promote better code organisation.

Before ES6 (ECMAScript 2015), JavaScript didn't have native support for modules. Developers had to use workarounds like Immediately Invoked Function Expressions (IIFEs) to achieve module-like behaviour. However, ES6 introduced built-in support for modules through the import and export keywords.

Exporting from a Module

you can export functionality from a module using the export keyword. There are two primary ways to export:

  1. Named Exports: This allows you to export multiple entities from a module.
// module.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Enter fullscreen mode Exit fullscreen mode
  1. Default Export: You can export a single "default" entity from a module. When importing, you can use any name for it.
// math.js
const multiply = (a, b) => a * b;
export default multiply;
Enter fullscreen mode Exit fullscreen mode

Importing a Module

To use functionality from another module, you need to import it into your current file using the import keyword.

// main.js
import { add, subtract } from './module.js';
import multiply from './math.js';

console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
console.log(multiply(2, 6)); // Output: 12
Enter fullscreen mode Exit fullscreen mode

Module Types

JavaScript supports two types of modules:

  1. ES6 Modules (ESM): The modern and recommended way of using modules. ESM is supported in modern browsers and Node.js versions using the --experimental-modules flag.

  2. CommonJS Modules (CJS): CommonJS is the module system used in older versions of Node.js. While it's still supported, it's not recommended for front-end development due to its synchronous nature, which can negatively impact performance.

Dynamic Imports

ES6 modules also support dynamic imports, allowing you to load modules dynamically at runtime. This can be beneficial for code splitting and lazy-loading in large applications.

// Dynamic import
import('./module.js')
  .then((module) => {
    // Use the imported module
    console.log(module.add(2, 3)); // Output: 5
  })
  .catch((error) => {
    console.error('Error loading module:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Why Use Modules?

  1. Encapsulation: Modules hide their implementation details and expose only the necessary functionality through exports, ensuring a clear interface for other parts of the application.

  2. Code Organization: Splitting code into modules enables developers to organize it more logically, making it easier to navigate and maintain large codebases.

  3. Reusability: Code written in modules can be reused across different projects, promoting the development of a library of useful functions and components.

  4. Dependency Management: Modules allow you to define dependencies explicitly. When one module depends on another, it can import the required functionality easily.

  5. Performance: As modules allow you to load only the necessary code, they can lead to better performance by reducing the initial loading time and organising the application's resource usage.

Top comments (0)