JavaScript Import & Export

Understanding ES6 Modules in Detail

📌 What is Import & Export?

In JavaScript, modules allow us to organize code into reusable pieces. We use export to share variables, functions, or classes, and import to bring them into another file.

📌 Types of Export

1. Named Export

You can export multiple things from a file. Import names must match exactly.

// module.js
export const pi = 3.14159;
export function area(r) {
  return pi * r * r;
}

// main.js
import { pi, area } from "./module.js";
console.log(area(5));

2. Default Export

A file can have only one default export. Import name can be anything.

// module.js
export default function greet() {
  return "Hello!";
}

// main.js
import hello from "./module.js";
console.log(hello());

📌 Combining Named & Default

// module.js
export const version = "1.0.0";
export function add(a, b) { return a + b; }
export default function subtract(a, b) { return a - b; }

// main.js
import subtract, { add, version } from "./module.js";

📌 Import Variations

Import Everything:

import * as utils from "./module.js";
console.log(utils.add(5,5));

Rename Import:

import { add as addition } from "./module.js";
console.log(addition(2,3));

Dynamic Import:

async function loadModule() {
  const module = await import("./module.js");
  console.log(module.add(4,6));
}

📌 Re-exporting

// math.js
export const square = x => x * x;

// index.js
export { square } from "./math.js";

// main.js
import { square } from "./index.js";

📌 Using <script type="module">

Normally we add JavaScript like this:

<script src="script.js"></script>

But to use ES6 Modules, we must write:

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

✅ Why do we need type="module"?

✅ Example with Module

// utils.js
export function greet() {
  return "Hello from module!";
}

// script.js
import { greet } from "./utils.js";
console.log(greet());

// index.html
<script src="script.js" type="module"></script>

📌 Comparison Table

Feature Named Export Default Export
Number per file Many Only one
Import name Must match Can be any name
Syntax import {x} import x
Use case Multiple utilities Main thing