Search code examples
javascriptecmascript-6ecmascript-5

Destructuring exported object in import statement


If I have a module that does export default { a: fn1, b: fn2 }, is there a way to import only fn1, like import { fn1 } from ...?


Solution

  • Although export { fn1, fn2 } will fix what you are searching for, there various ways to export and import. Some of them are listed below.

    One of the nice articles I have come across ES6 Modules in Depth

    NAME EXPORTS

    export fn1;
    export fn2;
    // OR
    export { fn1, fn2 };
    
    import { fn1, fn2 } from '';
    fn1();
    // OR
    import { fn1 as a, fn2 as b } from '';
    a();
    // OR
    import * as funcs from '';
    funcs.fn1();
    

    DEFAULT EXPORTS

    // ONLY ONE PER MODULE
    export default fn1;
    
    import fn1 from '';
    fn1();
    

    MIXED

    export default fn2;
    
    export fn1;
    
    import fn2, { fn1 } from '';
    import { default as fn2, fn1 } from ''; 
    fn1();