ES6 Modules
ES6 Modules give JavaScript a native way to split code into reusable,
self-contained files. With export and import, you can share
functions, classes, constants and objects between files — keeping your codebase
organised, maintainable and free from global-scope pollution.
They are the foundation of every modern JavaScript project.
import() for lazy-loading and code splitting
type="module"
Why Modules? Scripts vs ES6 Modules
Before ES6, JavaScript had no native module system. Developers shared code via
global variables or third-party solutions like
RequireJS (AMD) and
CommonJS (Node). These approaches were fragile —
globals polluted the window, scripts loaded in strict order, and name collisions were
common. ES6 Modules (ESM) solve all of this natively.
- Every variable lands on
window— easy collisions - Load order matters — wrong order breaks the page
- No native dependency tracking
- Requires IIFE hacks to avoid leaking globals
- No
import/export— use globals to share
- Each file has its own scope — zero global pollution
- Static
import— browser resolves the graph - Strict mode is on by default — safer code
- Deferred by default — no render-blocking
- Dynamic
import()for on-demand loading
Using type="module" in HTML
To use ES6 Modules in the browser, add type="module"
to your <script> tag.
This signals to the browser that the file is a module — it gets its own scope,
runs in strict mode, and is deferred automatically
(equivalent to defer).
window. No global leaks.
"use strict" is implied — you don't need to write
it yourself.file:// in most browsers.
thisthis is window,
inside a module this is undefined.<!-- Regular script — globals, blocking, no import/export -->
<script src="old.js"></script>
<!-- ES6 Module — own scope, strict, deferred, supports import -->
<script type="module" src="main.js"></script>
<!-- Inline module (same rules apply) -->
<script type="module">
import { greet } from "./utils.js";
greet("World");
</script>Named Exports
A named export gives a binding an explicit name. A module can have
as many named exports as needed. The importer must use the
exact same name (or alias it with as).
Use named exports when a module provides multiple related things — utility functions,
constants, helper classes, etc.
export directly before a declaration —
function, class, const, let.as to rename:
export { fn as doThing } — the public name differs from the internal one.
// ── 1. Inline export ───────────────────────────────────────
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export class Vector {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.sqrt(this.x ** 2 + this.y ** 2); }
}
// ── 2. Export list (declare first, export at bottom) ───────
function subtract(a, b) { return a - b; }
function multiply(a, b) { return a * b; }
export { subtract, multiply };
// ── 3. Aliased export ──────────────────────────────────────
function _internalHelper(x) { return x * 2; }
export { _internalHelper as double }; // public name is "double"
Default Exports
A default export is the primary value a module exposes — one per file, maximum. When importing, you don't use curly braces and you choose the local name freely. Default exports are ideal for modules that represent a single thing — a class, a component, a configuration object.
// ── Form 1: export default a class ─────────────────────────
// userService.js
export default class UserService {
constructor(baseUrl) { this.base = baseUrl; }
async getUser(id) {
const res = await fetch(`${this.base}/users/${id}`);
return res.json();
}
}
// ── Form 2: export default a function ──────────────────────
// formatDate.js
export default function formatDate(date) {
return new Intl.DateTimeFormat("en-IN").format(date);
}
// ── Form 3: export default an expression / object ──────────
// config.js
export default {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3,
};lodash-style helpers). Use default
exports for single-purpose modules — one class, one component, one hook. Mixing
both in one file is valid, but keep it intentional.
Import Syntax — All Forms
The import statement is static —
it must appear at the top of the file (outside any function or block) and the
specifier must be a string literal. The browser/bundler resolves all imports
before the module executes.
import statement before running any code.
// ── 1. Named import ────────────────────────────────────────
import { add, PI } from "./utils.js";
console.log(add(2, 3)); // 5
// ── 2. Named import with alias ─────────────────────────────
import { add as sum, multiply as times } from "./utils.js";
console.log(sum(4, 5)); // 9
// ── 3. Default import ──────────────────────────────────────
import UserService from "./userService.js"; // name is your choice
import formatDate from "./formatDate.js";
// ── 4. Default + named in one statement ────────────────────
import UserService, { ROLES, PERMISSIONS } from "./userService.js";
// ── 5. Namespace import (import everything as one object) ──
import * as MathUtils from "./utils.js";
console.log(MathUtils.add(1, 2)); // 3
console.log(MathUtils.PI); // 3.14159
// ── 6. Side-effect import (run module, import nothing) ─────
import "./polyfills.js"; // executes the file; no bindings imported
import "./styles.css"; // bundlers like Vite handle CSS imports too
Re-exports & Barrel Files
A barrel file (typically index.js)
aggregates
exports from multiple modules and re-exposes them through a single entry point.
This is a common pattern in React component libraries, utility packages, and feature folders.
Consumers import from one tidy path instead of deep file paths.
// ── Re-export named ────────────────────────────────────────
export { add, subtract } from "./math.js";
// ── Re-export all ──────────────────────────────────────────
export * from "./math.js";
export * from "./string.js";
export * from "./date.js";
// ── Re-export default as named ─────────────────────────────
export { default as UserService } from "./userService.js";
// ── Barrel file — src/utils/index.js ───────────────────────
export * from "./math.js";
export * from "./string.js";
export { default as UserService } from "./userService.js";
// Consumer — clean import path (no deep nesting) ───────────
import { add, UserService } from "./utils"; // resolves to utils/index.js
Dynamic import() — Lazy Loading
Static import is resolved at parse time and is
always eagerly loaded. Dynamic import() is a function-like
expression that returns a Promise — you call it at runtime, inside
conditions, inside event handlers, anywhere. This enables lazy loading
and code splitting — ship only what the user needs right now.
import(`./locales/${lang}.js`) — instead of bundling all
translations.
// ── Basic dynamic import ───────────────────────────────────
const { add } = await import("./utils.js");
console.log(add(2, 3)); // 5
// ── Default export via dynamic import ─────────────────────
const module = await import("./formatDate.js");
const formatDate = module.default; // access .default
// ── Lazy-load on user interaction ──────────────────────────
document.getElementById("openChart").addEventListener("click", async () => {
const { renderChart } = await import("./chart.js");
renderChart("#canvas", data);
});
// ── Dynamic specifier — load locale file ───────────────────
async function loadLocale(lang) {
try {
const { messages } = await import(`./locales/${lang}.js`);
return messages;
} catch {
const { messages } = await import("./locales/en.js"); // fallback
return messages;
}
}
// ── Conditional polyfill ───────────────────────────────────
if (!window.ResizeObserver) {
await import("./polyfills/resize-observer.js");
}import.meta — Module Metadata
Every module has access to import.meta — an object
that exposes metadata about the current module. The most useful property is
import.meta.url, which gives the absolute URL
of the current module file. Bundlers like Vite also add
import.meta.env for environment variables.
// ── import.meta.url — absolute URL of this module ─────────
console.log(import.meta.url);
// "https://example.com/js/utils.js"
// ── Resolve a relative file path from this module ──────────
const dataUrl = new URL("../data/config.json", import.meta.url).href;
const config = await fetch(dataUrl).then(r => r.json());
// ── import.meta.env (Vite / bundler specific) ──────────────
if (import.meta.env.DEV) {
console.log("Running in development mode");
}
const apiKey = import.meta.env.VITE_API_KEY; // from .env fileQuick Reference — Module Syntax Cheat Sheet
| Syntax | Type | Example | Notes |
|---|---|---|---|
| export const | Named inline | export const PI = 3.14; |
Immediately exports the binding |
| export { x, y } | Named list | export { add, sub }; |
Export at end of file — explicit control |
| export { x as y } | Named + alias | export { fn as doThing }; |
Public name differs from internal name |
| export default | Default | export default class App {} |
Only one per module; importer picks name |
| import { x } | Named import | import { add } from "./m.js"; |
Name must match the export exactly |
| import { x as y } | Named alias | import { add as sum } from "./m.js"; |
Rename on import side |
| import Def | Default import | import App from "./App.js"; |
No curly braces; any local name |
| import * as ns | Namespace | import * as Utils from "./m.js"; |
All named exports under one object |
| import "path" | Side-effect | import "./polyfill.js"; |
Runs module, imports nothing |
| export * from | Re-export all | export * from "./math.js"; |
Barrel pattern — forward all named exports |
| import() | Dynamic | const m = await import("./m.js"); |
Returns a Promise; used at runtime |
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.