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

后端 未结 5 726
旧时难觅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:59

    There aren't any definitive rules, but there are some conventions that people use to make it easier to structure or share code.

    When there is only one export in the entire file, there is no reason to make it named. Also, when your module has one main purpose, it could make sense to make that your default export. In those cases you can extra named exports

    In react for example, React is the default export, since that is often the only part that you need. You don't always Component, so that's a named export that you can import when needed.

    import React, {Component} from 'react';
    

    In the other cases where one module has multiple equal (or mostly equal) exports, it's better to use named exports

    import { blue, red, green } from 'colors';
    

提交回复
热议问题