Handling Multiple Default Exports in a Single File
In JavaScript/TypeScript modules, you can only have one default export per file. Attempting to declare multiple default exports will cause an error. Here’s how to properly structure your exports:
The Problem
// ❌ Incorrect (multiple default exports)
export default function ComponentA() { /* ... */ }
export default function ComponentB() { /* ... */ } // Error
Solutions
1. Single Default Export + Named Exports (Recommended)
// ✅ Correct - one default export
export default function MainComponent() { /* ... */ }
// Additional named exports
export function ComponentA() { /* ... */ }
export function ComponentB() { /* ... */ }
2. Export an Object as Default
// ✅ All components under one default export
const ComponentA = () => { /* ... */ };
const ComponentB = () => { /* ... */ };
export default {
ComponentA,
ComponentB
};
// Import usage:
// import MyComponents from './file';
// <MyComponents.ComponentA />
3. Combine Components in a Single Default Export
function ComponentA() { /* ... */ }
function ComponentB() { /* ... */ }
// ✅ Export as a single compound component
export default function Combined() {
return (
<>
<ComponentA />
<ComponentB />
</>
);
}
4. Split Into Separate Files (Best for Large Components)
components/
├── ComponentA.js // export default function ComponentA()
└── ComponentB.js // export default function ComponentB()
Importing Strategies
For solution #1 (named exports):
import MainComponent, { ComponentA, ComponentB } from './components';
For solution #2 (object export):
import Components from './components';
// Use as <Components.ComponentA />
TypeScript Considerations
When using TypeScript with compound exports (solution #2), define an interface:
interface ComponentExports {
ComponentA: React.FC;
ComponentB: React.FC;
}
const exports: ComponentExports = {
ComponentA: () => { /* ... */ },
ComponentB: () => { /* ... */ }
};
export default exports;
Best Practices
- One primary component per file – Makes components easier to find and maintain
- Use named exports for secondary utilities/components
- Keep files focused – If you need many exports, consider splitting into multiple files
- Be explicit – Clear export names help with code discovery
Common Pitfalls
- Accidental re-declaration of default export
- Circular dependencies when organizing exports
- Namespace collisions when combining many exports
- IDE confusion when scanning for default exports