Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint warning - Assign arrow function to a variable before exporting as module default

When I try to create and export an arrow function like this:

export default () => {};

I get this warning from ESLint:

Assign arrow function to a variable before exporting as module default

Of course i can assign it to a variable and then export it. But why can't i do it the other way? What is wrong with exporting an arrow function without assigning it to something?

like image 700
Hayk Sahakyan Avatar asked Mar 05 '26 03:03

Hayk Sahakyan


2 Answers

this will solve the issue:

const Name = () => {  }; 

export default Name

If you read eslint docs es-lint docs

Reports if a module's default export is unnamed. This includes several types of unnamed data types; literals, object expressions, arrays, anonymous functions, arrow functions, and anonymous class declarations.

Ensuring that default exports are named helps improve the grepability of the codebase by encouraging the re-use of the same identifier for the module's default export at its declaration site and at its import sites.

grepability: grep is a command for finding things, based on patterns. grep-ability would be the use of certain programming conventions that make it easier to find information.

like image 97
Yilmaz Avatar answered Mar 06 '26 15:03

Yilmaz


It is not an Error. It is a Warning. So you CAN do it. However, it is not good practice.

Here's the thing: when you say () => {}, you're declaring an anonymous function with no name. When you say var foo = function() {} you are declaring an anonymous function, then assigning it as the value to the foo variable.

It's a small difference, but it matters if you care about writing code that is easy to reuse and debug.

When you name the function your debugger is able to label it correctly for you in the debugging pane, but if you declare an anonymous function you'll just see anonymous function. This can be a pain when debugging, so by putting in a little repetitive effort when it's easy (when you name it) you can potentially save yourself (or other people who get to read/use your code) a headache later when debugging.

If you are sure what you do is exporting anonymous functions, ESLint's docs tell you how to disable the error notification:

"import/no-anonymous-default-export": ["error", {
  "allowArray": false,
  "allowArrowFunction": false,
  "allowAnonymousClass": false,
  "allowAnonymousFunction": false,
  "allowCallExpression": true, // The true value here is for backward compatibility
  "allowLiteral": false,
  "allowObject": false
}]
like image 29
Francesco Perticarari Avatar answered Mar 06 '26 16:03

Francesco Perticarari