Reputation: 855
I get the warning in the consle:"Assign object to a variable before exporting as module default import/no-anonymous-default-export."
This is coming from my .js functions which export several functions as default. I am not sure how to get rid of, while still being able to export several functions as default and keep the code simple as per below.
function init() {}
function log(error) {
console.error(error);
}
export default {
init,
log,
};
I could write the file as:
export default function init() {}
export function log(error) {
console.error(error);
}
Is there a setting I need to change, something I can do about it?
Upvotes: 44
Views: 60356
Reputation: 1482
My friends, you can use these rules inside your .eslintrc.cjs
or .eslintrc.js
and change them based on your needs.
For example, sometimes you need to export your codes without naming, like tailwind.config.js
, postcss.config.js
or axios
config which are object
s, in that case, you can use "allowObject": true
rules: {
//...
"import/no-anonymous-default-export": ["error", {
"allowArray": false,
"allowArrowFunction": false,
"allowAnonymousClass": false,
"allowAnonymousFunction": false,
"allowCallExpression": false, // backward compatibility -> e.g. export default foo(bar)
"allowNew": false,
"allowLiteral": false,
"allowObject": true
}]
}
eslint-plugin-import -> no-anonymous-default-export
Upvotes: 4
Reputation: 11
Asain your data in a variable, then export as default.
//Example
const data = [
{
id: 1,
name: 'Bertie Yates',
age: 29,
image:
'https://res.cloudinary.com/diqqf3eq2/image/upload/v1595959131/person-2_ipcjws.jpg',
},
{
id: 3,
name: 'Larry Little',
age: 36,
image:
'https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883423/person-4_t9nxjt.jpg',
},
{
id: 4,
name: 'Sean Walsh',
age: 34,
image:
'https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883417/person-3_ipa0mj.jpg',
},
]
export default data
Upvotes: 1
Reputation: 370639
It's telling you to give the object being exported a name before exporting, to make it more likely that the name used is consistent throughout the codebase. For example, change to:
function init() {}
function log(error) {
console.error(error);
}
const logger = {
init,
log,
};
export default logger;
(Give it whatever name makes most sense in context - logger
is just an example)
But if you're going to export multiple things, using named exports would make a bit more sense IMO. Another option is to do:
export function init() {}
export function log(error) {
console.error(error);
}
and then import them as:
import { init, log } from './foo.js';
Upvotes: 61