Conflicting multiple default exports in the same file

Loading

Handling Multiple Default Exports in a Single File

A common JavaScript/TypeScript error occurs when you attempt to have multiple export default statements in the same module. This causes a compilation error because:

“Only one default export allowed per module”

The Problematic Code

// ❌ Wrong - will cause error
export default function ComponentA() {
  return <div>First Component</div>;
}

export default function ComponentB() {
  return <div>Second Component</div>;
}

Correct Solutions

1. Single Default Export with Named Exports (Recommended)

// ✅ Correct approach
function ComponentA() {
  return <div>First Component</div>;
}

function ComponentB() {
  return <div>Second Component</div>;
}

// One default export
export default ComponentA;
// Plus named exports
export { ComponentB };

2. Export an Object as Default

// ✅ Alternative approach
function ComponentA() { /* ... */ }
function ComponentB() { /* ... */ }

export default {
  ComponentA,
  ComponentB
};

// Import usage:
// import MyComponents from './file';
// <MyComponents.ComponentA />

3. Combine Components in a Single Default Export

// ✅ For related components
function ComponentA() { /* ... */ }
function ComponentB() { /* ... */ }

function CombinedComponents() {
  return (
    <>
      <ComponentA />
      <ComponentB />
    </>
  );
}

export default CombinedComponents;

Best Practices

  1. One primary export per file: Follow the principle of one logical unit per file
  2. Use named exports: For secondary exports from a file
  3. Meaningful file names: Helps identify the primary export
  4. Index files: Use index.js to re-export from multiple files

Common Use Cases

For utility files:

// utils/math.js
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
// No default export needed

For React components:

// components/Form.js
function Input() { /* ... */ }
function SubmitButton() { /* ... */ }

// Export Input as default since it's the main component
export default Input;
// Export SubmitButton as named export
export { SubmitButton };

TypeScript Considerations

TypeScript enforces the single default export rule even more strictly. The solutions above work the same way in TypeScript files.

Remember: While you can only have one export default per file, you can have as many named exports (export const, export function) as needed.

Leave a Reply

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