Assign object to variable before exporting as module default

avatar

Borislav Hadzhiev

Sat Apr 09 20222 min read

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.

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 re-use of the same identifier when exporting a module 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.

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.

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