Conflicting multiple default exports in the same file

Loading

Handling Multiple Default Exports in a Single File

Having multiple default exports in one file is invalid JavaScript syntax and will cause errors. Here’s how to properly structure your exports:

The Problem

Invalid code:

// components.js
const Button = () => <button>Click</button>;
export default Button;

const Card = () => <div className="card"></div>;
export default Card; // SyntaxError: Duplicate export of 'default'

Correct Solutions

1. Single Default Export (Recommended)

// components.js
const Button = () => <button>Click</button>;
const Card = () => <div className="card"></div>;

// Export as named exports
export { Button, Card };

// OR export one as default
export default Button;
export { Card }; // named export

2. Multiple Components in One File

// Button.js
const Button = () => <button>Click</button>;
export default Button;

// Card.js
const Card = () => <div className="card"></div>;
export default Card;

3. Object Export Pattern

// components.js
const Button = () => <button>Click</button>;
const Card = () => <div className="card"></div>;

export default {
  Button,
  Card
};

// Import usage:
import components from './components';
const { Button, Card } = components;

Best Practices

  1. One default export per file – Follows standard conventions
  2. Use named exports for multiple components
  3. Split components into separate files – Better for code organization
  4. Be consistent across your project

Common Patterns

1. Component + Styles Export

// Button.js
export const ButtonStyles = { color: 'blue' };
const Button = () => <button style={ButtonStyles}>Click</button>;
export default Button;

2. Main Component + Subcomponents

// Card.js
export const CardHeader = () => <div className="header"></div>;
export const CardBody = () => <div className="body"></div>;

const Card = () => (
  <div className="card">
    <CardHeader />
    <CardBody />
  </div>
);
export default Card;

TypeScript Considerations

TypeScript will enforce single default exports more strictly. The same patterns apply but with type annotations:

// components.tsx
interface ButtonProps {
  text: string;
}
const Button: React.FC<ButtonProps> = ({ text }) => <button>{text}</button>;
export default Button;

Migration Strategy

If refactoring existing code with multiple default exports:

  1. Identify all default exports in the file
  2. Convert all but one to named exports
  3. Update all import statements in other files
  4. Consider splitting into multiple files if components are large

Leave a Reply

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