Show List

ES6 Modules

ES6 modules provide a way to organize and structure JavaScript code into reusable components. Modules allow you to export functions, variables, classes, or objects from one file and import them into another file, making it easier to manage dependencies and promote code reusability. Here's an explanation of ES6 modules with code examples:

Exporting from a Module:

In a module file (e.g., module.js), you can export functions, variables, classes, or objects using the export keyword:


// module.js export const PI = 3.14; export function greet(name) { return `Hello, ${name}!`; } export class Person { constructor(name) { this.name = name; } greet() { return `Hello, my name is ${this.name}.`; } }

Importing from a Module:

In another file where you want to use the exported entities, you can import them using the import keyword:


// app.js import { PI, greet, Person } from './module.js'; console.log(PI); // Output: 3.14 console.log(greet('Alice')); // Output: Hello, Alice! const person = new Person('Bob'); console.log(person.greet()); // Output: Hello, my name is Bob.

Default Exports:

You can also export a default entity from a module. There can only be one default export per module.


// module.js const defaultGreeting = 'Hello, world!'; export default defaultGreeting;

// app.js import defaultGreeting from './module.js'; console.log(defaultGreeting); // Output: Hello, world!

Exporting All Entities:

You can export all entities from a module using the * as syntax:


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

// app.js import * as utils from './module.js'; console.log(utils.PI); // Output: 3.14 console.log(utils.greet('Alice')); // Output: Hello, Alice!

Renaming Imports:

You can rename imports using the as keyword:


// app.js import { PI as piValue } from './module.js'; console.log(piValue); // Output: 3.14

Code Example:

Here's how you can use ES6 modules to organize your code:


// module.js export function greet(name) { return `Hello, ${name}!`; } export function farewell(name) { return `Goodbye, ${name}!`; }

// app.js import { greet, farewell } from './module.js'; console.log(greet('Alice')); // Output: Hello, Alice! console.log(farewell('Bob')); // Output: Goodbye, Bob!

ES6 modules provide a clean and efficient way to organize and manage code in large JavaScript projects, promoting code reusability and maintainability. They also enable better encapsulation and dependency management, making it easier to work collaboratively on projects.


    Leave a Comment


  • captcha text