JavaScript modules allow you to break down your code into smaller, reusable pieces. They promote better code organization, maintainability, and reusability. Modules in JavaScript can export and import functions, objects, or primitive values, making it easier to manage dependencies and avoid global scope pollution.
JavaScript modules use the export and import keywords to share and consume code between files.
The export statement is used to export functions, objects, or primitive values from a module so they can be used in other modules.
Example: Exporting a Function
// math.js
export function add(a, b) {
return a + b;
}
This example demonstrates how to export a function from one module.
// constants.js
export const PI = 3.14;
export const E = 2.71;
This example shows how to export variables from a module.
// person.js
export class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
This example demonstrates how to export a class from a module.
// utils.js
export default function log(message) {
console.log(message);
}
This example shows how to use default export in a module.
The import statement is used to import functions, objects, or primitive values from another module.
Example: Importing a Function
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5
This example demonstrates how to import a function from another module.
// main.js
import { PI, E } from './constants.js';
console.log(PI); // Output: 3.14
console.log(E); // Output: 2.71
This example shows how to import variables from another module.
// main.js
import { Person } from './person.js';
const person = new Person('John');
person.greet(); // Output: Hello, my name is John
This example demonstrates how to import a class from another module.
// main.js
import log from './utils.js';
log('This is a default export'); // Output: This is a default export
This example shows how to import a default export from another module.
Dynamic imports allow you to import modules conditionally or on demand, providing a way to optimize performance and load modules asynchronously.
Example: Dynamic Import
// main.js
async function loadModule() {
const module = await import('./math.js');
console.log(module.add(2, 3)); // Output: 5
}
loadModule();
This example demonstrates how to dynamically import a module in JavaScript.
Here are some important notes and best practices when using JavaScript modules:
JavaScript modules provide a powerful way to organize and manage your code, promoting better maintainability and reusability. By understanding and using modules, you can write cleaner and more modular JavaScript code.