Module 48 : Javascript Import and Export.
1. What are in JavaScript?
Definition
reusable pieces of code that can be exported from one file and imported into another. They help organize code, reduce repetition, and improve maintainability.
π§ Why Use ?
Encapsulation: Keep functionality isolated.
Reusability: Use code across multiple files.
Maintainability: Easier to manage large codebases.
Collaboration: Teams can work on separate files.
2. Exporting in JavaScript
πΉ A. Named Exports
You can export multiple values from a file using named exports.
// mathUtils.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Each item is exported by name and must be imported using the same name.
πΉ B. Default Export
can have one default export. Useful when a exports only one thing.
// greeting.js export default function greet(name) { return `Hello, ${name}!`; }
3. Importing in JavaScript
πΉ A. Importing Named Exports
// app.js import { add, subtract } from './mathUtils.js'; console.log(add(10, 5)); // Output: 15
You must use the exact names that were exported.
πΉ B. Importing Default Export
// app.js import greet from './greeting.js'; console.log(greet('Rehana')); // Output: Hello, Rehana!
πΉ C. Renaming Imports
import { add as addition } from './mathUtils.js'; console.log(addition(5, 5)); // Output: 10
4. Combining Exports
can have both default and named exports.
// user.js export const getUser = () => ({ name: 'Ali', age: 30 }); export default class User { constructor(name) { this.name = name; } }
// main.js import User, { getUser } from './user.js'; const user = new User('Sara'); console.log(getUser()); // { name: 'Ali', age: 30 }
5. File Structure
project/ │ ├── app.js ├── mathUtils.js └── greeting.js
Each file is treated as a separate. Use import and export to share logic between files.
6. Exercises
Exercise 1: Create a Math Module
Task:
Create a file calculator.js with the following exports:
multiply (named)
divide (named)
calculate (default) which takes 2 numbers and an operator (+, -, *, /).
Solution:
// calculator.js export const multiply = (a, b) => a * b; export const divide = (a, b) => a / b; export default function calculate(a, b, operator) { switch (operator) { case '+': return a + b; case '-': return a - b; case '*': return multiply(a, b); case '/': return divide(a, b); default: return null; } }
// testCalculator.js import calculate, { multiply, divide } from './calculator.js'; console.log(calculate(4, 2, '*')); // 8 console.log(multiply(3, 3)); // 9
Exercise 2: Create a User
Create a User class with login() and logout() methods.
Export it as the default export.
Create a named export function isUserLoggedIn().
Solution:
// userModule.js export default class User { constructor(name) { this.name = name; this.loggedIn = false; } login() { this.loggedIn = true; console.log(`${this.name} logged in`); } logout() { this.loggedIn = false; console.log(`${this.name} logged out`); } } export const isUserLoggedIn = (user) => user.loggedIn;
7. Common Mistakes to Avoid
Mistake
Example
Fix
Forgetting file extension
import foo from './module'
Always use .js: import foo from './module.js'
Using default without default export
import x from './file.js'
Ensure the module has a default export
Mixing CommonJS and ES modules
require() with import
Stick to one system, preferably ES Modules
8. Tips
live coding:
Create two simple files and import/export functions.
Use visuals: Show boundaries work using folder/file.
Show errors: Let them see what happens if a details is not correctly imported (helpful for debugging skills).
Group exercise: Assign into groups to create utility collaboration and share with each other.
9. Research Insights
Modern JavaScript (ES6+)
system (import/export) is native to ES6 (ECMAScript 2015). Before that, developers used:
CommonJS (require/module.exports) – still used in Node.js.
AMD or UMD for browsers.
Performance Benefits
Browsers and bundlers (like Webpack, Vite) can tree-shake unused exports, making applications smaller and faster.
10. Summary
Concept
Syntax Example
Named Export
export const x = 5;
Default Export
export default function() {}
Named Import
import { x } from './file.js';
Default Import
import myFunc from './file.js';
Rename Import
import { x as y } from './file.js';
Create a module called stringUtils.js with:
Named export: capitalize(str)
Default export: a function that reverses a string.
Import both into another file and test them.
No comments:
Post a Comment