Tutorials JavaScript ES6 Modules
Ch 51 / 78
Chapter 51 Intermediate 9 min read JavaScript

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.

Advertisement
What you'll learn
Why modules exist and how they differ from scripts
Named exports vs default exports — when to use each
All import syntax — named, default, aliased, namespace, side-effect
Re-exporting and barrel files for clean public APIs
Dynamic import() for lazy-loading and code splitting
Module features — strict mode, deferred execution, CORS & 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.

Classic Scripts (Old Way)
Global scope, no isolation, order-dependent loading.
  • 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
ES6 Modules (Modern)
Own scope, explicit exports, static dependency graph.
  • 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).

Module characteristics vs regular scripts
Own scope
always
Variables declared in a module are not on window. No global leaks.
Strict mode
always
"use strict" is implied — you don't need to write it yourself.
Deferred loading
always
Modules don't block HTML parsing. They run after the document is parsed.
Executed once
cached
Even if imported by multiple files, a module runs only once — its exports are cached.
CORS required
network
Modules must be served over HTTP(S) — they won't work from file:// in most browsers.
Top-level this
undefined
Unlike scripts where this is window, inside a module this is undefined.
HTML — Loading a module
<!-- 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.

named
Inline export
Add export directly before a declaration — function, class, const, let.
named
Export list
Declare first, then export a list at the bottom — great for controlling what's public.
named
Aliased export
Use as to rename: export { fn as doThing } — the public name differs from the internal one.
default
Default export
Only one per file. The importer chooses the local name freely — no braces needed.
utils.js — Named exports (all forms)
// ── 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.

JavaScript — Default export forms
// ── 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,
};
💡
Named vs Default — rule of thumb: Use named exports for utility libraries that export many things (e.g. 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 resolution flow
1
Parse — discover all static imports
The JS engine scans the file and finds every import statement before running any code.
2
Fetch — download dependency files
The browser fetches each imported module URL (one request per unique module, cached after first fetch).
3
Link — connect exported bindings
The engine links each imported name to the live binding in the exporting module. Updates to the export are reflected automatically.
4
Evaluate — run the module code
Modules are evaluated depth-first. Circular imports are handled — each module only executes once.
JavaScript — Every import syntax form
// ── 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.

JavaScript — Re-export forms + barrel pattern
// ── 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.

Dynamic import — use cases
📄
Route-based splitting
Load a page's module only when the user navigates to that route — core technique in React Router, Vue Router.
🎛️
Feature gating
Load a heavy charting library only when the user opens the dashboard — not on every page load.
🌐
Localisation
Load only the user's locale file — import(`./locales/${lang}.js`) — instead of bundling all translations.
⚙️
Conditional polyfills
Detect browser support and load a polyfill only when needed — no unnecessary bytes for modern browsers.
JavaScript — Dynamic import() patterns
// ── 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.

JavaScript — import.meta usage
// ── 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 file

Quick 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel