JavaScript Modules

JavaScript modules allow you to break down your code into smaller, reusable pieces, making it easier to manage and maintain. Modules enable you to export functions, objects, or values from one file and import them into another.

Module Syntax

  1. Exporting Modules
  2. Importing Modules
  3. Default Export
  4. Named Exports
  5. Re-exporting Modules
  6. Dynamic Imports

1. Exporting Modules

Modules are created by exporting variables or functions from a file.

Example:

// math.js
export function add(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}

Try It Now

2. Importing Modules

You can import the exported functions or variables into another file using the import keyword.

Example:

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

console.log(add(5, 3));       // Output: 8
console.log(subtract(5, 3));  // Output: 2

Try It Now

3. Default Export

A module can have one default export, which is often used for exporting a single entity (like a class or a function).

Example:

// logger.js
export default function log(message) {
    console.log(message);
}

Try It Now

Importing a Default Export:

// main.js
import log from './logger.js';

log('Hello, World!');  // Output: Hello, World!

Try It Now

4. Named Exports

You can have multiple named exports in a single module. These are imported using curly braces.

Example:

// math.js
export const PI = 3.14;
export function multiply(a, b) {
    return a * b;
}

Try It Now

Importing Named Exports:

// main.js
import { PI, multiply } from './math.js';

console.log(PI);                // Output: 3.14
console.log(multiply(2, 3));    // Output: 6

Try It Now

5. Re-exporting Modules

You can re-export an imported module to make it available to other modules.

Example:

// utils.js
export * from './math.js';

Try It Now

Importing Re-exported Modules:

// main.js
import { add } from './utils.js';

console.log(add(2, 3));  // Output: 5

Try It Now

6. Dynamic Imports

Dynamic imports allow you to import modules on demand. This is useful for loading code only when needed.

Example:

// main.js
function loadModule() {
    import('./math.js').then(module => {
        console.log(module.add(2, 3));  // Output: 5
    });
}

loadModule();

Try It Now

Using Modules in HTML

To use modules in a browser, you need to add the type="module" attribute to the <script> tag.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Modules</title>
</head>
<body>
    <script type="module" src="main.js"></script>
</body>
</html>

Try It Now

Conclusion

JavaScript modules are a fundamental feature for creating modular, maintainable code. They enable you to break down your application into smaller parts, making it easier to manage and scale.