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

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

    1st Method:-

    export foo; //so that this can be used in other file
    
    import {foo} from 'abc'; //importing data/fun from module
    

    2nd Method:-

    export default foo;  //used in one file
    
    import foo from 'blah'; //importing data/fun from module
    

    3rd Method:-

    export = foo;
    
    import * as foo from 'blah';
    

    The above methods roughly compile to the following syntax below:-

    //all export methods

    exports.foo = foo; //1st method
    exports['default'] = foo; //2nd method
    module.exports = foo; //3rd method
    

    //all import methods

    var foo = require('abc').foo; //1st method
    var foo = require('abc')['default']; //2nd method
    var foo = require('abc'); //3rd method
    

    For more information, visit to Default keyword explaination

    Note:- There can be only one export default in one file.

    So whenever we are exporting only 1 function, then it's better to use default keyword while exporting

提交回复
热议问题