Assign object to variable before exporting as module default

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
2 min

banner

# Assign object to variable before exporting as module default

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.

assign object to variable before exporting as default

Here is an example of how the error occurs.

utils.js
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.

# Assign the object to a variable

To solve the error, assign the object to a variable and use a default export on the next line.

utils.js
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.

App.js
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.

App.js
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, };
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev