Named export vs exporting an object

前端 未结 2 1642
旧巷少年郎
旧巷少年郎 2021-01-03 22:58

Why does this work:

const str = \'stuff\';
export {
  str
};

But not this:

export default {
  str: \'stuff\'
};


        
相关标签:
2条回答
  • 2021-01-03 23:28

    There are two styles of exports in ES6 -- named exports, and the default export. Named exports get exported with syntax like this:

    export const str = 'stuff';
    // or
    const str = 'stuff';
    export { str };
    

    Default exports go like this:

    const obj = { str: 'stuff' };
    export default obj;
    // or 
    export default {
      str: 'stuff'
    };
    

    The difference shows up when you import. With the first, you need to include braces:

    import { str } from 'myModule'; // 'stuff', from the first example
    

    Without braces, it imports the default export:

    import myModule from 'myModule'; //  {str: 'stuff'}, from the second example
    
    0 讨论(0)
  • 2021-01-03 23:32

    The main reason of the export statement is to be used to export functions, objects or primitives from a given file (or module).

    But you need an identifier in order to be exported (so that it can be imported via import in another script).

    You can simply do:

    export const obj = {
      str: 'stuff'
    };
    

    During the import, you will be able to use the same name obj to refer to the corresponding value.

    And import it like:

    import { obj } from 'myLib';
    
    0 讨论(0)
提交回复
热议问题