简体   繁体   English

如何解决 ESLint 错误“Prefer default export...”?

[英]How to resolve the ESLint error "Prefer default export ..."?

I have the following module, in which there is a named function... eslint ( airbnb ) is raising an error:我有以下模块,其中有一个命名函数...... eslint ( airbnb ) 正在引发错误:

8:1 error Prefer default export import/prefer-default-export 8:1 错误 Prefer default export import/prefer-default-export

How should I restructure my code to comply to this requirement?我应该如何重组我的代码以符合此要求?

exports / imports should be at the beginning of the code... exports / imports 应该在代码的开头......

module模块

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);
};

The general idea is to change your named export to a default export - the syntax to use is export default <something> .一般的想法是将您的命名导出更改为默认导出 - 使用的语法是export default <something> Default exports aren't named, so you'll either have to remove the getCategories :默认导出未命名,因此您要么必须删除getCategories

export default async () => {

Or, if you like the function being in a usefully-named variable, you'll have to define the function ahead of time, and then export it:或者,如果您喜欢该函数位于一个有用命名的变量中,则必须提前定义该函数,然后将其导出:

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;

(though if the module/file name is getCategories , which it probably should be, this wouldn't be very useful, I think) (虽然如果模块/文件名是getCategories ,它可能应该是,这不会很有用,我认为)

Both of the above approaches pass the no-use-before-define rule as well.上述两种方法也都通过了no-use-before-define规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM