ES Modules: import export and dynamic import
Use named exports, default exports, namespace imports, and lazy-load code with dynamic import() for performance.
Review: ES Module Basics
ES Modules give every file its own scope. Named exports share specific values; default exports share the primary value. The bundler or browser resolves imports at load time.
// Named exports
export const API_BASE = '/api/v1';
export function formatDate(d) { return d.toISOString().slice(0, 10); }
// Default export
export default class ApiClient {
constructor(base = API_BASE) { this.base = base; }
}Tree Shaking — Why Named Exports Matter
Bundlers (Rollup, esbuild, Vite) eliminate unused exports. If you import only { formatDate }, the bundler removes everything else from the bundle. Named exports enable tree shaking; import * as utils can prevent it.
// consumers/report.js — only needs formatDate
import { formatDate } from './utils.js';
// Bundler omits API_BASE and ApiClient from this chunkAll lessons in this course
- ES Modules: import export and dynamic import
- npm and package.json: dependencies scripts
- Vite: dev server and build
- Bundling Concepts: tree shaking code splitting