JavaScript Modules

JavaScript modules allow you to break up your code into separate files, making it easier to maintain and manage. They help in organizing code into reusable and logically related units. This tutorial covers how to use modules in JavaScript, including importing and exporting functionalities.

Introduction to Modules

Modules are a way to encapsulate and organize code. By using modules, you can separate different parts of your application into files, making it easier to manage dependencies and maintain code. JavaScript modules are implemented using the ES6 module syntax, which includes `import` and `export` statements.

Exporting Modules

To make a piece of code available to other modules, you use the `export` keyword. There are two types of exports: named exports and default exports.


// Named export
export const pi = 3.14159;
export function calculateArea(radius) {
    return pi * radius * radius;
}

// Default export
export default class Circle {
    constructor(radius) {
        this.radius = radius;
    }

    area() {
        return pi * this.radius * this.radius;
    }
}

                

Importing Modules

To use the functionalities from another module, you use the `import` keyword. You can import named exports, default exports, or both.


// Importing named exports
import { pi, calculateArea } from './math.js';

console.log(pi); // Outputs: 3.14159
console.log(calculateArea(5)); // Outputs: 78.53975

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

const circle = new Circle(5);
console.log(circle.area()); // Outputs: 78.53975

                

Module Resolution

When importing modules, JavaScript resolves the module paths. The paths can be relative or absolute. For relative paths, you need to specify the path from the current module's location. For absolute paths, the modules are resolved based on the configuration of the build system.


// Relative import
import { myFunction } from './utils/myFunction.js';

// Absolute import (based on configuration)
import { myUtility } from '/utils/myUtility.js';

                

Dynamic Imports

Dynamic imports allow you to load modules asynchronously at runtime using the `import()` function. This can be useful for lazy loading or code splitting.


// Example of dynamic import
async function loadModule() {
    const module = await import('./module.js');
    module.doSomething();
}

loadModule();