Conflicting multiple default exports in the same file

Loading

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

  1. One primary component per file – Makes components easier to find and maintain
  2. Use named exports for secondary utilities/components
  3. Keep files focused – If you need many exports, consider splitting into multiple files
  4. Be explicit – Clear export names help with code discovery

Common Pitfalls

  1. Accidental re-declaration of default export
  2. Circular dependencies when organizing exports
  3. Namespace collisions when combining many exports
  4. IDE confusion when scanning for default exports

Leave a Reply

Your email address will not be published. Required fields are marked *