πŸ“¦ Import and Export (ES Modules)

Modern JavaScript uses ES Modules (ESM) to organize code into multiple files. Instead of writing everything in a single file, you can split your code into reusable modules and connect them using export and import.

>>"Write once, reuse everywhere. Modules make JavaScript scalable."

πŸ“– What is a Module?

A module is simply a JavaScript file. Every module has its own scope, meaning variables and functions inside one file are not automatically available in another file.

Example:

Project Structure

project/
│── math.js
│── app.js
│── user.js
│── index.html

🎯 Why Use Modules?

  • βœ… Better code organization
  • βœ… Reusable functions
  • βœ… Easy maintenance
  • βœ… Avoid global variables
  • βœ… Faster development
  • βœ… Cleaner architecture

πŸ“¦ Export in JavaScript

export makes variables, functions, classes, or objects available for use in other modules.

1️⃣ Named Export

Named exports allow exporting multiple values from the same file.

math.js

export const PI = 3.14159;

export function add(a, b) {
    return a + b;
}

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

Import them like this:

app.js

import { PI, add, subtract } from "./math.js";

console.log(PI);
console.log(add(5, 2));
console.log(subtract(10, 3));

Note

Named imports must match the exported names exactly.

2️⃣ Exporting Later

math.js

const PI = 3.14;

function add(a, b) {
    return a + b;
}

export { PI, add };

3️⃣ Renaming Exports

math.js

const PI = 3.14;

export { PI as CirclePI };

app.js

import { CirclePI } from "./math.js";

console.log(CirclePI);

🌟 Default Export

A module can have only one default export.

user.js

export default function greet() {
    console.log("Hello World");
}

Import it without curly braces.

app.js

import greet from "./user.js";

greet();

Note

The imported name can be anything because it's the default export.

Example

import sayHello from "./user.js";

sayHello();

🎯 Default Export of Variables

config.js

const API_URL = "https://example.com";

export default API_URL;

app.js

import url from "./config.js";

console.log(url);

🏷 Default Export of Classes

Person.js

export default class Person {
    constructor(name){
        this.name = name;
    }

    greet(){
        console.log("Hello " + this.name);
    }
}

app.js

import Person from "./Person.js";

const p = new Person("John");
p.greet();

πŸ“š Multiple Named Exports

math.js

export const PI = 3.14;

export function square(n){
    return n*n;
}

export function cube(n){
    return n*n*n;
}

app.js

import { PI, square, cube } from "./math.js";

console.log(square(5));
console.log(cube(3));

🎨 Import Everything

Use * as to import all named exports into a single object.

app.js

import * as MathUtils from "./math.js";

console.log(MathUtils.PI);
console.log(MathUtils.square(5));
console.log(MathUtils.cube(4));

🎯 Rename During Import

app.js

import { add as sum } from "./math.js";

console.log(sum(5,5));

πŸ“¦ Mixing Default and Named Export

math.js

export const PI = 3.14;

export function add(a,b){
    return a+b;
}

export default function greet(){
    console.log("Hello");
}

app.js

import greet, { PI, add } from "./math.js";

greet();

console.log(PI);
console.log(add(4,5));

πŸ“ Re-export

math.js

export function add(a,b){
    return a+b;
}

index.js

export { add } from "./math.js";

app.js

import { add } from "./index.js";

console.log(add(2,3));

πŸ“₯ Dynamic Import

Dynamic imports load modules only when needed, which can improve application performance.

app.js

async function loadMath(){

    const math = await import("./math.js");

    console.log(math.add(5,5));
}

loadMath();

Note

Dynamic import returns a Promise and is commonly used for lazy loading.

🌐 Using Modules in HTML

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Modules</title>
</head>
<body>

<script type="module" src="app.js"></script>

</body>
</html>

Note

Without type="module", ES module imports will not work in the browser.

πŸ“‚ Example Project

Folder Structure

project/
β”‚
β”œβ”€β”€ index.html
β”œβ”€β”€ app.js
β”œβ”€β”€ math.js
└── user.js

math.js

math.js

export function add(a,b){
    return a+b;
}

export function multiply(a,b){
    return a*b;
}

user.js

user.js

export default function welcome(){
    console.log("Welcome");
}

app.js

app.js

import welcome from "./user.js";
import { add, multiply } from "./math.js";

welcome();

console.log(add(5,3));

console.log(multiply(5,3));

⚠️ Common Errors

ErrorReasonSolution
Cannot use import statementModule not enabledUse type="module"
Module not foundWrong file pathCheck relative path and extension
Named export not foundIncorrect export nameMatch the exact exported identifier
Unexpected token 'export'Environment doesn't support ES ModulesEnable ESM or use a bundler/runtime configuration

πŸ’‘ Best Practices

  • Use named exports for utility functions.
  • Use default exports when a file exposes one primary value.
  • Keep modules small and focused on a single responsibility.
  • Use meaningful file and export names.
  • Avoid circular dependencies between modules.
  • Always include the correct relative path (for example, ./math.js) when importing in browsers.

🧠 Quick Comparison

FeatureNamed ExportDefault Export
Number per fileUnlimitedOne
Uses curly braces when importingYesNo
Name must match exportYes (unless aliased)No
Best use caseMultiple utilitiesMain function, class, or object of a module

πŸŽ‰ Summary

You learned how to:

  1. Create JavaScript modules.
  2. Export variables, functions, classes, and objects.
  3. Use named exports and default exports.
  4. Import modules in different ways, including aliasing and namespace imports.
  5. Re-export modules through a central file.
  6. Use dynamic imports for lazy loading.
  7. Load ES modules correctly in the browser with type="module".
  8. Follow best practices and troubleshoot common module errors.
>>πŸš€ Mastering JavaScript modules is a key step toward building clean, maintainable, and scalable applications.