Last updated: Mar 6, 2024
Reading timeยท2 min
The "Assign object to a variable before exporting as module default" error occurs when we try to export an anonymous object using a default export.
To solve the error, assign the object to a variable and use a default export on the next line.
Here is an example of how the error occurs.
function sum(a, b) { return a + b; } const multiply = (a, b) => { return a * b; }; // ๐๏ธ anonymous default export // โ๏ธ Assign object to a variable before exporting as module default eslint import/no-anonymous-default-export export default { sum, multiply, };
The issue is that we're using a default export to export an anonymous object.
To solve the error, assign the object to a variable and use a default export on the next line.
function sum(a, b) { return a + b; } const multiply = (a, b) => { return a * b; }; // ๐๏ธ assign to variable const doMath = { sum, multiply, }; // ๐๏ธ use default export export default doMath;
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.
Now you are still able to import the module using a default import.
import doMath from './utils'; console.log(doMath.sum(10, 10)); // ๐๏ธ 20 console.log(doMath.multiply(10, 10)); // ๐๏ธ 100
This approach encourages the reuse of the same identifier when exporting a module and importing it.
By default, the ESlint rule warns us about 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.
function sum(a, b) { return a + b; } const multiply = (a, b) => { return a * b; }; // eslint-disable-next-line import/no-anonymous-default-export export default { sum, multiply, };
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.