Solve - Unexpected default export of anonymous function

avatar

Borislav Hadzhiev

Sun Apr 10 20222 min read

banner

Photo by Axel Holen

Solve - Unexpected default export of anonymous function #

The "Unexpected default export of anonymous function" warning is caused when we try to export an anonymous function using a default export. To solve the error, give the function a name before exporting it.

unexpected default export of anonymous function

Here is an example of how the warning is caused.

Header.js
// 👇️ default export for anonymous function // ⛔️ Unexpected default export of anonymous function // eslint import/no-anonymous-default-export export default function () { return <h1>hello world</h1>; }

The issue here is that we're using a default export to export an anonymous function.

To solve the error, give a name to the function before using a default export.

Header.js
// 👇️ give name to function that's being exported export default function Header() { return <h1>hello world</h1>; }

IMPORTANT: If you are exporting a variable (or an arrow function) as a default export, you have to declare it on 1 line and export it on the next. You can't declare and default export a variable on the same line.

Header.js
const Header = () => { return <h1>hello world</h1>; }; export default Header;

Now you are still able to import the function using a default import.

App.js
import Header from './Header'; const App = () => ( <div> <Header /> </div> ); export default App;
This approach encourages the re-use of the same identifier when exporting a function and importing it.

By default, the eslint rule warns us for all types of anonymous default exports, e.g. arrays, functions, classes, objects, etc.

If you want to disable the rule for a single line, you can use a comment.

Header.js
// eslint-disable-next-line import/no-anonymous-default-export export default function () { return <h1>hello world</h1>; }
The comment should be placed right above the code with the anonymous default export.

Alternatively, you can update what the import/no-anonymous-default-export rule should check for in your .eslintrc file.

The options section of the Github repository shows the complete default configuration for the rule, which you can tweak in the rules object of your .eslintrc file.

Use the search field on my Home Page to filter through my more than 1,000 articles.