如何解决 ESLint 错误 "Prefer default export ..."?
How to resolve the ESLint error "Prefer default export ..."?
我有以下模块,其中有一个命名函数...
eslint ( airbnb ) 出现错误:
8:1 error Prefer default export import/prefer-default-export
我应该如何重构我的代码以符合此要求?
导出/导入应该在代码的开头...
模块
import fetch from 'node-fetch';
const normalize = json => json.categories.map(category => ({
id: category.catId,
name: category.catName,
}));
export const getCategories = async () => {
const response = await fetch(
'http://mockbin.org/bin/0535d3fb-74f6-43a6-b4d4-461d84795be4',
{
method: 'GET',
headers: { accept: 'application/json' },
},
);
const json = await response.json();
return normalize(json);
};
一般的想法是将您的命名导出更改为默认导出 - 使用的语法是 export default <something>
。默认导出未命名,因此您要么必须删除 getCategories
:
export default async () => {
或者,如果您喜欢将函数放在命名有用的变量中,则必须提前定义函数,然后将其导出:
const getCategories = async () => {
const response = await fetch(
'http://mockbin.org/bin/0535d3fb-74f6-43a6-b4d4-461d84795be4',
{
method: 'GET',
headers: { accept: 'application/json' },
},
);
const json = await response.json();
return normalize(json);
};
export default getCategories;
(虽然如果 module/file 名称是 getCategories
,它可能应该是,我认为这不会很有用)
以上两种方法也都通过了no-use-before-define
规则。
我有以下模块,其中有一个命名函数... eslint ( airbnb ) 出现错误:
8:1 error Prefer default export import/prefer-default-export
我应该如何重构我的代码以符合此要求?
导出/导入应该在代码的开头...
模块
import fetch from 'node-fetch';
const normalize = json => json.categories.map(category => ({
id: category.catId,
name: category.catName,
}));
export const getCategories = async () => {
const response = await fetch(
'http://mockbin.org/bin/0535d3fb-74f6-43a6-b4d4-461d84795be4',
{
method: 'GET',
headers: { accept: 'application/json' },
},
);
const json = await response.json();
return normalize(json);
};
一般的想法是将您的命名导出更改为默认导出 - 使用的语法是 export default <something>
。默认导出未命名,因此您要么必须删除 getCategories
:
export default async () => {
或者,如果您喜欢将函数放在命名有用的变量中,则必须提前定义函数,然后将其导出:
const getCategories = async () => {
const response = await fetch(
'http://mockbin.org/bin/0535d3fb-74f6-43a6-b4d4-461d84795be4',
{
method: 'GET',
headers: { accept: 'application/json' },
},
);
const json = await response.json();
return normalize(json);
};
export default getCategories;
(虽然如果 module/file 名称是 getCategories
,它可能应该是,我认为这不会很有用)
以上两种方法也都通过了no-use-before-define
规则。