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:-
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