`export const` vs. `export default` in ES6

前端 未结 6 878
悲哀的现实
悲哀的现实 2020-11-22 08:50

I am trying to determine if there is any big differences between these two, other than being able to import with export default by just doing:

i         


        
6条回答
  •  一向
    一向 (楼主)
    2020-11-22 08:53

    Minor note: Please consider that when you import from a default export, the naming is completely independent. This actually has an impact on refactorings.

    Let's say you have a class Foo like this with a corresponding import:

    export default class Foo { }
    
    //the name 'Foo' could be anything, since it's just an
    //identifier for the default export
    import Foo from './Foo'
    

    Now if you refactor your Foo class to be Bar and also rename the file, most IDEs will NOT touch your import. So you will end up with this:

    export default class Bar { }
    
    //the name 'Foo' could be anything, since it's just an
    //identifier for the default export.
    import Foo from './Bar'
    

    Especially in Typescript, I really appreciate named exports and the more reliable refactoring. The difference is just the lack of the default keyword and the curly braces. This btw also prevents you from making a typo in your import since you have type checking now.

    export class Foo { }
    
    //'Foo' needs to be the class name. The import will be refactored
    //in case of a rename!
    import { Foo } from './Foo'
    

提交回复
热议问题