Named Exports
Named Exports
Section titled “Named Exports”Introduction
Section titled “Introduction”Named exports let you export multiple values from a module. Each exported value has a specific name that must match when importing.
Exporting
Section titled “Exporting”// 📁 utils.js
// Inline exportexport const PI = 3.14159;export function add(a, b) { return a + b; }export class Calculator {}
// Or export at the endconst PI = 3.14159;function add(a, b) { return a + b; }class Calculator {}export { PI, add, Calculator };Importing
Section titled “Importing”// 📁 main.jsimport { PI, add } from './utils.js';console.log(add(PI, 2)); // 5.14159Import All
Section titled “Import All”import * as Utils from './utils.js';console.log(Utils.add(1, 2)); // 3console.log(Utils.PI); // 3.14159Utils.Calculator; // classRenaming
Section titled “Renaming”// Rename on exportexport { add as sum, PI as pi };
// Rename on importimport { add as sum, PI as pi } from './utils.js';console.log(sum(1, 2)); // 3Multiple Named Exports
Section titled “Multiple Named Exports”// 📁 helpers.jsexport const formatDate = (date) => date.toISOString();export const formatCurrency = (amount) => `$${amount.toFixed(2)}`;export const formatPhone = (phone) => phone.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');Re-exporting (Barrel Files)
Section titled “Re-exporting (Barrel Files)”// 📁 index.js — barrel fileexport { User } from './user.js';export { formatDate } from './helpers.js';export { API_BASE_URL } from './constants.js';
// Then import from the barrel:// import { User, formatDate } from './index.js';Summary
Section titled “Summary”- Named exports export multiple values with specific names
- Import with exact names or
import * as - Use
asfor renaming - Barrel files re-export for cleaner imports