Modules in JavaScript
Modules in JavaScript
function farewell() {
console.log("Goodbye!");
}
greet();
farewell();
Modular Code Example:
● File: greetings.js
javascript
export function greet() {
console.log("Hello!");
}
greet();
farewell();
Explanation:
● In the modular example, greetings.js contains only the greeting-related
code, while main.js uses it. This separation makes it easier to find and fix
issues or add new features.
Practical Applications
Using Modules in Frameworks:
● React: React components are modular files.
javascript
// File: Button.js
export default function Button() {
return <button>Click Me!</button>;
}
// File: App.js
import Button from './Button.js';
function App() {
return (
<div>
<Button />
</div>
);
}
● Vue.js: Each Vue component is essentially a module.
Real-World Application Example:
● Imagine a dynamic web application where authentication, user data, and
UI components are in separate modules. This structure ensures changes in
one module don’t disrupt others.