JavaScript ES Modules: Named & Default Exports, Tree-Shaking & Dynamic Imports

In early JavaScript, applications were single monolithic scripts polluting the global window object. ES Modules (ECMAScript Modules / ESM) introduced official, standardized language-level modularity in ES6, allowing software systems to be organized into clean, reusable, encapsulated files.

1. Named Exports & Imports

// mathUtils.js
export const PI = 3.14159;

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

export function subtract(a, b) {
    return a - b;
}
// app.js
import { add, PI } from "./mathUtils.js";

console.log("Sum:", add(10, 20)); // 30
console.log("PI Value:", PI);

2. Default Exports

// StudentService.js
export default class StudentService {
    static getStudentById(id) {
        return { id, name: "Vikram" };
    }
}
// main.js (No curly braces needed for default exports!)
import StudentService from "./StudentService.js";

const student = StudentService.getStudentById(101);

3. Dynamic Imports (import()) - Code Splitting

Allows loading modules on-demand only when a user triggers an action (saving initial page load time):

button.addEventListener("click", async () => {
    // Loaded dynamically on-demand!
    const { generatePDFReport } = await import("./pdfGenerator.js");
    generatePDFReport();
});

University Exam Corner (BCA Examination Notes)

Exam Question: "Compare CommonJS (Node.js legacy) and ES Modules (ESM)."

FeatureCommonJS (CJS)ES Modules (ESM)
Syntaxrequire() / module.exportsimport / export
Loading NatureSynchronous & Dynamic (at runtime)Asynchronous & Static (at parse time)
Tree-ShakingDifficult / Not supportedNatively supported

Next Step

How do you write pure functions, currying, and memoization pipelines? Proceed to: JavaScript Functional Programming & Currying →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

Classes & OOP →

Packaging and exporting reusable classes.

Functional Modules →

Exporting pure utility functions.

Project Setup & Bundlers →

Setting up type="module" and script tags.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!