1. Named Exports
A named export in JavaScript and TypeScript allows you to export multiple variables, functions, or classes from a single file. Unlike default exports, which only allow one primary value per module, named exports are ideal for sharing utility functions and keeping your codebase highly modular.
How to use Named Exports
1. Inline Exporting
You can export variables or functions directly as you declare them:-
You can export variables or functions directly as you declare them:-
// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const PI = 3.14159;
2. Exporting at the Bottom
Alternatively, you can declare your items first and export them together at the bottom of the file:-
// mathUtils.js
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
export { multiply, divide };
How to Import Named Exports
When importing named exports, you must wrap the exact names in curly braces
{}.// app.js
import { add, PI } from './mathUtils.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159
Useful Tricks
- Renaming: You can use the
askeyword to rename an export if it conflicts with an existing variable in your file:-import { add as sum } from './mathUtils.js'; - Importing Everything: You can import all exported members at once into a single object using
* as: import * as math from './mathUtils.js'; console.log(math.add(2, 3));
We can export components using export default or named exports and import them using "Import"
In one file only one default export can be there and no limit on named export components.
componentName.js
export default componentName;
import ComponentName from componentName;
2.
No comments:
Post a Comment