Search code examples
javascripteslintes6-moduleseslint-config-airbnb

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:

8:1 error 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...

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

Solution

  • The general idea is to change your named export to a default export - the syntax to use is export default <something>. Default exports aren't named, so you'll either have to remove the 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)

    Both of the above approaches pass the no-use-before-define rule as well.