JavaScript Modules: Import and Export Explained
Why Modules Are Needed
As applications grow, keeping all code inside one file becomes difficult.
Problems with large single files:
Hard to read
Hard to maintain
Difficult to debug
Code duplication
Naming conflicts
Poor team collaboration
Example of a Bad Large File
function calculateTax(amount) {
return amount * 0.18;
}
function formatCurrency(amount) {
return `$${amount}`;
}
function validateEmail(email) {
return email.includes("@");
}
function sendEmail(email) {
console.log("Sending email to:", email);
}
function generateInvoice() {
console.log("Invoice generated");
}
As the project grows:
Hundreds of functions get added
Finding code becomes difficult
Multiple developers editing same file causes conflicts
What Are Modules?
Modules allow you to split code into separate files.
Each file can contain:
Functions
Variables
Classes
Constants
These can be shared between files using:
export
import
Real-World Analogy
Think of modules like departments in a company.
Each department handles its own responsibility.
Modules work the same way in applications.
Basic Module Structure
project/ │ ├── math.js ├── user.js ├── app.js
Exporting Functions or Values
What is Export?
export makes functions or values available to other files.
Named Export Example
math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Importing Modules
Importing Named Exports
app.js
import { add, subtract } from "./math.js";
console.log(add(10, 5));
console.log(subtract(10, 5));
Output
15 5
How Import/Export Works
Exporting Variables
config.js
export const appName = "Inventory System"; export const version = "1.0.0";
Importing Variables
app.js
import { appName, version } from "./config.js";
console.log(appName);
console.log(version);
Exporting Multiple Items
A module can export:
Functions
Variables
Arrays
Objects
Classes
Example
user.js
export const users = ["Ali", "Sara"];
export function getUserCount() {
return users.length;
}
Import Example
app.js
import { users, getUserCount } from "./user.js";
console.log(users);
console.log(getUserCount());
Default Exports
What is a Default Export?
A module can have one main export using default.
Default Export Example
logger.js
export default function log(message) {
console.log(message);
}
Importing Default Export
app.js
import log from "./logger.js";
log("Application started");
Important Difference
Named exports require curly braces.
import { add } from "./math.js";
Default exports do not.
import log from "./logger.js";
Default vs Named Exports
Example of Renaming Default Import
logger.js
export default function log(message) {
console.log(message);
}
app.js
import printMessage from "./logger.js";
printMessage("Hello");
Default imports can use any name.
Combining Named and Default Exports
math.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
export default function multiply(a, b) {
return a * b;
}
Importing Combined Exports
app.js
import multiply, { PI, add } from "./math.js";
console.log(PI);
console.log(add(2, 3));
console.log(multiply(2, 3));
File Dependency Diagram
Module Import/Export Flow
Benefits of Modular Code
1. Better Organization
Code is separated by responsibility.
Example:
2. Easier Maintenance
You can update one module without affecting the entire project.
3. Reusability
Modules can be reused across different parts of the application.
4. Easier Debugging
Smaller files are easier to inspect and test.
5. Team Collaboration
Different developers can work on different modules independently.
Example Project Structure
project/ │ ├── app.js │ ├── modules/ │ ├── auth.js │ ├── database.js │ ├── payment.js │ └── email.js
Real-World Example
payment.js
export function calculateTotal(price, tax) {
return price + tax;
}
app.js
import { calculateTotal } from "./payment.js";
const total = calculateTotal(100, 18);
console.log(total);
Common Beginner Mistakes
1. Forgetting File Extension
Incorrect:
import { add } from "./math";
Correct:
import { add } from "./math.js";
2. Using Wrong Import Type
Incorrect:
import add from "./math.js";
If add was exported as named export.
3. Forgetting Curly Braces
Incorrect:
import add from "./math.js";
Correct:
import { add } from "./math.js";
Before Modules vs After Modules
Before
huge-app.js - 5000+ lines - all logic mixed together
After
auth.js payment.js email.js database.js app.js
Cleaner and easier to maintain.
Best Practices
Practice Exercise
Step 1: Create math.js
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
Step 2: Create app.js
import { add, multiply } from "./math.js";
console.log(add(5, 10));
console.log(multiply(5, 10));
Key Takeaways
Final Notes
Modern JavaScript development heavily depends on modules.
They are used in:
React
Node.js
Next.js
Vue
Backend applications
Frontend applications
Understanding modules early helps you write:
Scalable code
Cleaner architecture
Professional applications
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!