Modules (import/export)
Master JavaScript modules! Learn to organize code across files with import/export and module patterns.
Master JavaScript modules! Learn to organize code across files with import/export and module patterns. This hands-on tutorial focuses on practical implementation of modules (import/export) concepts.
Modules (import/export)
As your application grows, putting all code in one file becomes a nightmare. Modules let you split your code into separate files, making it easier to maintain and reuse.
1. What are Modules? π¦
What is it? A module is simply a JavaScript file that exports code for other files to use.
Why use it?
- Organization: Break complex apps into small, manageable pieces.
- Reusability: Write a function once (e.g.,
calculateTax) and use it in multiple files. - Encapsulation: Variables in a module are private by default. They don't pollute the global scope.
How it works:
We use export to expose code and import to use it.
2. Named Exports π€
Use this when you want to export multiple things from a single file.
File: mathUtils.js
File: main.js
3. Default Exports π―
Use this when a file has one main purpose (like a React component or a main class). You can only have one default export per file.
File: User.js
File: main.js
4. Renaming Imports & Importing All π
Sometimes you have naming conflicts or just want to import everything.
5. Dynamic Imports β‘
Standard imports are static (at the top of the file). Dynamic imports load code on demand (e.g., when a user clicks a button). This speeds up initial page load!
AI Mentor
Confused about "JavaScript modules, named exports, default exports, and dynamic imports"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4How many Default Exports can a file have?
Key Takeaways
β
Modules split code into files.
β
Named Exports (export const x) for multiple items.
β
Default Exports (export default x) for one main item.
β
import { x } for named, import x for default.
β
Dynamic Imports (import()) for performance.
What's Next?
Congratulations! You've finished the Core JavaScript module! π
Next, we dive into the DOM (Document Object Model) to make web pages interactive.
Keep coding! π