Named exports are the backbone of modular JavaScript. They enable **tree shaking** in bundlers (unused exports are removed from the bundle). You can **rename on export** (`export { fn as utility }`) or **rename on import** (`import { fn as utility }`). Re-exporting from an index file creates clean public APIs.
1Understanding Named Exports
Named exports are the backbone of modular JavaScript. They enable tree shaking in bundlers (unused exports are removed from the bundle). You can rename on export (export { fn as utility }) or rename on import (import { fn as utility }). Re-exporting from an index file creates clean public APIs.
Create an index.js that re-exports from multiple files to give consumers a clean single import point.
// helpers.js
export function debounce(fn, delay) { /* ... */ }
export function throttle(fn, interval) { /* ... */ }
export function memoize(fn) { /* ... */ }
// index.js (re-export aggregator)
export { debounce, throttle, memoize } from './helpers.js';
export { default as UserService } from './userService.js';
// consumer.js
import { debounce, UserService } from './index.js';2Practical Example
Here is a real-world application of Named Exports showing how it is used in production JavaScript code.
// Renaming exports
export { longFunctionName as shortName };
export { internalName as publicName };
// Import with alias
import { debounce as debounceFn } from './helpers.js';3Best Practices
Follow these guidelines when working with Named Exports:
1. Export at declaration for clarity
2. Use export lists at the bottom for a clear module summary
3. Create index.js files to aggregate and re-export
Tip: Create an index.js that re-exports from multiple files to give consumers a clean single import point.
// helpers.js
export function debounce(fn, delay) { /* ... */ }
export function throttle(fn, interval) { /* ... */ }
export function memoize(fn) { /* ... */ }
// index.js (re-export aggregator)
export { debounce, throttle, memoize } from './helpers.js';
export { default as UserService } from './userService.js';
// consumer.js
import { debounce, UserService } from './index.js';