Modules Import/Export

Introduction
Modules in JavaScript allow developers to split code into reusable, organized, and maintainable files. Using import and export, you can share functions, variables, or classes between different files. This makes large projects easier to manage and improves code readability.

What are JavaScript Modules
A module is simply a JavaScript file that contains code you want to reuse. Each module has its own scope, which helps avoid conflicts between variables and functions.

Why Use Modules
Modules help keep code clean and organized
They allow reuse of functions and logic across files
They improve maintainability in large projects
They reduce the risk of naming conflicts

Exporting in JavaScript
Export is used to make variables, functions, or classes available to other files.

Named Export
You can export multiple items from a file by name

Example
export const name = “Ali”
export function greet() {
return “Hello”
}

Default Export
A file can have one default export

Example
export default function welcome() {
return “Welcome to JavaScript”
}

Importing in JavaScript
Import is used to bring exported code into another file.

Import Named Exports
import { name, greet } from “./file.js”

Import Default Export
import welcome from “./file.js”

Import Everything
import * as utils from “./file.js”

Using Modules in HTML
To use modules in the browser, you must define the script type as module

Example
script type=”module” src=”app.js” script

Best Practices
Use meaningful file names
Keep modules small and focused
Use default export for main functionality
Use named exports for multiple utilities

Common Use Cases
Sharing utility functions across files
Organizing large applications into smaller parts
Reusing code in different projects
Building scalable frontend and backend applications

Conclusion
JavaScript modules using import and export are essential for writing clean and scalable code. They help developers structure applications efficiently and promote code reuse.

Home » Advanced JavaScript > ES6+ Features > Modules Import/Export