Understanding ES6 Modules: Import and Export in JavaScript
Overview
This lesson delves into the concept of ES6 modules, focusing on the import and export keywords. We'll explore how these features allow us to break down large JavaScript files into more manageable individual components, making our code cleaner and easier to understand. 📦✨
Key Concepts
1. ES6 Modules: A way to organize and share code between different files. 📁🔄
2. export keyword: Used to make functions, constants, or objects available for use in other files. 📤
3. export default: Specifies the main export from a file. There can only be one per file. 🥇
4. import keyword: Used to bring in functionality from other files. 📥
Practical Example: Math Module 🧮
Let's create a simple math.js file to demonstrate these concepts:
// math.js
const pi = 3.1415962;
function doublePi() {
return pi * 2;
}
function triplePi() {
return pi * 3;
}
export default pi;
export { doublePi, triplePi };
In this example:
- pi is the default export
- doublePi and triplePi are named exports
Using the Math Module 🔢
Now, let's use our math.js module in another file:
// index.js
import PI, { doublePi, triplePi } from "./math.js";
console.log(PI); // 3.1415962
console.log(doublePi()); // 6.2831924
console.log(triplePi()); // 9.4247886Note:
- The default export can be renamed (e.g., PI instead of pi)
- Named exports must use the exact name 🔤
Import Variations 🎨
1. Default Import:
import PI from "./math.js";- Can be named anything
- Maps to the export default in the source file
2. Named Imports:
import { doublePi, triplePi } from "./math.js";- Must use exact names
- Maps to the export { ... } in the source file
3. Wildcard Import:
import * as mathUtils from "./math.js";
console.log(mathUtils.default); // pi value
console.log(mathUtils.doublePi()); // 6.2831924- Imports everything as an object
- Less preferred as it's less clear 🚫
Why Use Modules? 🤔
1. Code Organization: Break down large files into smaller, focused ones. 📂
2. Readability: Each file has a clear purpose. 👀
3. Maintainability: Easier to find and fix issues. 🔧
4. Reusability: Share code between different parts of your app. ♻
ES6 Modules vs Node.js require 🆚
- ES6: import/export (part of JavaScript)
- Node.js: require (Node.js specific)
// Node.js style
var react = require('react');ES6 modules are preferred in modern web development due to:
1. Clear syntax 🎨
2. Browser compatibility (with Babel) 🌐
3. Better code splitting 🧩
Best Practices 👍
1. Use one default export per file.
2. Name default imports for clarity.
3. Use named exports for multiple items.
4. Avoid wildcard imports (`import * as ...`) for better readability.
5. Keep modules focused and small.
Next Steps 🚀
In the upcoming lesson, we'll practice more with import and export through a coding challenge. If you're comfortable with the concepts here, head to the next lesson and put your skills to the test! 💪🧠