Why and when to use default export over named exports in es6 Modules?

后端 未结 5 714
旧时难觅i
旧时难觅i 2020-12-05 10:11

I have referred all the questions in stackoverflow. But none of the suggested why and when to use default export.

I just saw that default can be metioned \"When th

5条回答
  •  渐次进展
    2020-12-05 10:52

    It's somewhat a matter of opinion, but there are some objective aspects to it:

    • You can have only one default export in a module, whereas you can have as many named exports as you like.

    • If you provide a default export, the programmer using it has to come up with a name for it. This can lead to inconsistency in a codebase, where Mary does

      import foo from "./foo";
      

      ...but Joe does

      import getFoo from "./foo";
      

      In constrast, with a named export, the programmer doesn't have to think about what to call it unless there's a conflict with another identifier in their module. It's just

      import { foo } from "./foo";
      

      ...(with an as getFoo if necessary to avoid a conflict).

    • With a named export, the person importing it has to specify the name of what they're importing, which means they get a nice early error if they try to import something that doesn't exist.

    • If you consistently only use named exports, programmers importing from modules in the project don't have to think about whether what they want is the default or a named export.

提交回复
热议问题