The text starts here~
Overview
When we try to export an anonymous function using the default export, it results in an "Unexpected default export of anonymous function" warning. To resolve this error, give the function a name before exporting the function.
Here is an example to show how the warning occurs.
// 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 problem with the above code is that we use the default export to export an anonymous function.
name
To resolve this error, give the function a name before exporting the function.
// Header.js
// 👇️ give name to function that's being exported
export default function Header() {
return <h1>hello world</h1>;
}
Important : if you want to export a variable (or an arrow function) as a default export, you must declare it on one line and export it on the next. You cannot declare and export a variable by default on the same line.
// Header.js
const Header = () => {
return <h1>hello world</h1>;
};
export default Header;
Now you can still import functions using default imports.
// App.js
import Header from './Header';
const App = () => (
<div>
<Header />
</div>
);
export default App;
This approach encourages reuse of the same identifier when exporting and importing functions.
By default, the eslint
rule warns us about anonymous default exports of all types, such as arrays, functions, classes, objects, etc.
Comment out a single-line rule
If you want to disable single-line rules, you can use comments.
// Header.js
// eslint-disable-next-line import/no-anonymous-default-export
export default function () {
return <h1>hello world</h1>;
}
Comments should be placed right above code with anonymous default exports.
Alternatively, you can in the .eslintrc
file, update import/no-anonymous-default-export
what should be checked.
The options section of the Github repository shows the full default configuration for this rule, which you can adjust in the rules object of your .eslintrc
file.
Summarize
To resolve the warning, either name the default exported function or use the eslint
single-line comment to release the line of code.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。