Modules and Import/Export
40 minBefore ES6, JavaScript had no native module system. Now, **ES Modules (ESM)** are the standard. They allow you to split code into separate files, making it maintainable, reusable, and testable.
**Named Exports** allow you to export multiple values from a file (`export const a = 1;`). You import them using curly braces (`import { a } from './file.js'`).
**Default Exports** allow you to export a single main value (`export default class User...`). You import it without braces and can name it whatever you want (`import User from './file.js'`).
Modules are strict by default (`'use strict'`), have their own scope (top-level variables aren't global), and are deferred (execute after parsing).
Key Concepts
- Named vs. Default Exports.
- Import syntax (`import ... from ...`).
- Module Scope vs. Global Scope.
- Dynamic Imports (`import()`).
- Tree Shaking (removing unused exports).
Learning Objectives
Master
- Structuring a project with modules
- Using named and default exports correctly
- Renaming imports with `as`
- Loading modules dynamically for performance
Develop
- Code architecture
- Dependency management
- Understanding build tools (bundlers)
Tips
- Prefer Named Exports for libraries/utilities (better for tree-shaking and refactoring).
- Use Default Exports for main components or classes (one per file).
- Use `import * as utils` to namespace multiple imports.
- Use dynamic imports (`await import(...)`) for code splitting and lazy loading.
Common Pitfalls
- Mixing CommonJS (`require`) and ESM (`import`) without proper configuration.
- Forgetting the file extension (`.js`) in native browser imports.
- Circular dependencies (Module A imports B, B imports A) – can cause runtime issues.
- Thinking imports are hoisted (they are, but it's best practice to keep them at the top).
Summary
- Modules organize code into files.
- ESM is the native standard.
- Exports share code, Imports use it.
- They enable modern build workflows.
Exercise
Create a module that exports a function and import it in another file.
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './math.js';
console.log(add(5, 3));
Exercise Tips
- Try using default export: export default function add(a, b) { ... }.
- Export multiple functions and import them all: import { add, subtract, multiply } from './math.js'.
- Use named exports with aliases: import { add as sum } from './math.js'.
- Experiment with dynamic imports: const module = await import('./math.js').