Modern JavaScript development depends on modules in which code is split into smaller, reusable and maintainable code.
First try to understand the problem,if you have single file
//app.js
function add(a,b) return a +b
function multiply(a,b)return a*b
Now as code grows
- Files becomes too large
- Code becomes hard to read
- Duplication arise
- Resuing the code is painful This where modules comes into picture:
What is Module
A module is simply a file that contains code(function, variables, classes)that you export and reuse into another files.
Exporting function or variables
export const PI = 3.14
export function add(a,b){
return a+b
}
You can export multiple things from a module
Importing Modules
To use export Modules,you import it
// app.js
import { add, PI } from './math.js';
console.log(add(2, 3)); //
5 console.log(PI); // 3.14
You must use exact name when importing modules.
Default vs Named Exports
Default Export:
A module can have one default export
// greet.js
export default function greet(name) {
return `Hello, ${name}`;
}
Import it like this:
import greet from './greet.js';
console.log(greet('Alice'))
**Named Export**
// utils.js
`export const square = x => x * x;
export const cube = x => x * x * x;
Import:
import { square, cube } from './utils.js';`
In Short:
- Modules help to organize code
- Modules prevent naming conflicts
- Modules helps in better readability
- Modules can be reused in entire application
Top comments (0)