JavaScript Export and Import (ES6 Modules)
ES6 introduced modules, allowing you to split code into multiple files using export
import
. This makes JavaScript more modular, maintainable, and reusable.
🔹 1. Exporting in JavaScript
Exports make functions, objects, or variables available in other files. There are two types of exports:
- Named Exports
- Default Exports
📝 Named Exports
Named exports allow exporting multiple values from a module.
Example: math.js
Importing Named Exports (app.js
)
✔ Use curly braces {}
to import specific items.
✔ The names must match the exported ones.
Import with an Alias
✔ Useful for renaming conflicting imports.
📝 Default Export
A file can have one default export, which can be imported without curly braces.
Example: greet.js
Importing a Default Export (app.js
)
✔ No curly braces {}
needed.
✔ You can rename the imported default export.
🔹 2. Exporting and Importing Everything (*
)
You can export everything from a module using *
(wildcard).
Example: Importing All from math.js
✔ Everything is imported as an object (MathUtils
).
✔ Useful for grouping related exports.
🔹 3. Mixing Named and Default Exports
A module can have both default and named exports.
Example: tools.js
Importing in app.js
✔ Default and named exports can be imported together.
🔹 4. Dynamic Imports (import()
)
Instead of static import
, JavaScript allows dynamic importing using import()
, which returns a Promise.
Example: Dynamic Import
✔ Useful for lazy loading (only loads when needed).
✔ Can be used conditionally or inside functions.
🔹 5. Common Issues and Fixes
🛑 "Uncaught SyntaxError: Cannot use import statement outside a module"
✅ Solution:
- Ensure
type="module"
in HTML - Use a local server (
live-server
,http-server
, or a bundler like Webpack/Vite).
🛑 "Module Not Found"
✅ Solution:
- Use correct file paths (
./
or absolute paths). - Ensure the file exists and has the
.js
extension.
🔹 6. Summary
Feature | Named Export | Default Export |
---|---|---|
Syntax | export { item } | export default item |
Import Syntax | import { item } | import item |
Curly Braces | Required {} | Not required |
Multiple Exports | ✅ Yes | ❌ No (only one) |
Renaming | ✅ Using as | ✅ Any name |
🚀 ES6 modules improve code organization and reuse!