Search code examples
javascriptreactjscompilation

How can I get rid of the warning import/no-anonymous-default-export in React?


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?


Solution

  • 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';