import / export) & Dynamic ImportsES Modules (ESM) provide a standardized module format for organizing JavaScript code into separate maintainable files. Modules establish explicit file scopes, preventing global namespace pollution.
flowchart TD
ModuleA["auth.js (Export Module)"] --> ExportNamed["export const login = () => {}"]
ModuleA --> ExportDefault["export default class AuthManager {}"]
ModuleA --> ModuleB["app.js (Import Module)"]
ModuleB --> ImportNamed["import { login } from './auth.js'"]
ModuleB --> ImportDefault["import AuthManager from './auth.js'"]
| Style | Export Syntax | Import Syntax |
|---|---|---|
| Named Exports | export const api = "..."; |
import { api } from "./module.js"; |
| Default Export | export default function main() {} |
import main from "./module.js"; |
| Aliased Import | export const log = ...; |
import { log as customLogger } from "..."; |
| Dynamic Import | N/A | const mod = await import("./module.js"); |
// Simulated ES Module Export & Import Structure
// ==========================================
// File: utils/mathUtils.js (Module Exports)
// ==========================================
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// Default export
export default function calculator(operation, a, b) {
if (operation === "add") return add(a, b);
return multiply(a, b);
}
// ==========================================
// File: main.js (Module Imports)
// ==========================================
// import calculator, { PI, add as sum } from "./utils/mathUtils.js";
// Demonstrating Dynamic Import (Lazy Loading)
async function loadHeavyFeature() {
console.log("Loading module dynamically...");
// const heavyModule = await import("./heavyFeature.js");
// heavyModule.run();
}
import { fn } from "./utils.js").export default.import() for Code Splitting: Use import("module-path") to lazy-load heavy modules on demand inside event handlers to improve initial bundle loading speed.Explain the difference between import { user } from "./user.js" and import user from "./user.js".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.