React ES6 Modules
⚛️ React ES6 Modules
ES6 introduced modules to organize code into reusable pieces.
React heavily depends on this concept — every component is usually its own module.
A module can export values (variables, functions, components) and another file can import them.
🔹 Export in ES6
There are two types of exports:
Named Export
Default Export
✅ 1. Named Export
Export Example:
Or:
Import Example:
You must use the exact same name while importing.
✅ 2. Default Export
Use this when exporting one main value from a file.
Export:
Import:
You can rename default imports.
🚀 Modules in React Components
Example Component File (Car.js):
Importing into Another File:
🧩 Modules with Named + Default Export
Import:
📦 Index Files for Cleaner Imports
Instead of importing many files individually:
Create an index.js:
Then import:
✔ Cleaner and modular!
🎯 Why ES6 Modules Are Important in React?
| Benefit | Why it matters |
|---|---|
| Organizes code | Each component in its own file |
| Reusability | Import components anywhere |
| Maintainability | Easier structure in large apps |
| Avoids global variable pollution | Safer and scalable |
🧠 Summary
| Type | Syntax | Rename Allowed | Use Case |
|---|---|---|---|
| Named Export | export { name } | ❌ No | Multiple exports |
| Default Export | export default xyz | ✅ Yes | One main export |
