Destructuring a default export object

前端 未结 2 609
暖寄归人
暖寄归人 2020-11-28 06:22

Can I destructure a default export object on import?

Given the following export syntax (export default)

const foo = ...
function bar()         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 07:08

    Dynamic Imports

    To add to Bergi's answer, note that in the case of dynamic imports, since the returned module is an object, you can use destructuring assignment to import it:

    (async function () {
      const { default: { foo, bar } } = await import('./export-file.js');
      console.log(foo, bar);
    })();
    

    Why this works

    import operates much differently in different contexts. When used at the beginning of a module, in the format import ... from ... , it is a static import, which has the limitations discussed in Bergi's answer.

    When used inside a program in the form import('./filename.js'), it is considered a dynamic import. The dynamic import operates very much like a function that resolves to an object (as a combination of named exports and the default export, which is assigned to the default property), and can be destructured as such.

    In the case of the questioner's example, await import('./export-file.js') will resolve to:

    {
      default: {
        foo: ...,
        bar: function bar() {...}
      }
    }
    

    From here, you can just use nested destructuring to directly assign foo, and bar:

    const { default: { foo, bar } } = await import('./export-file.js');
    

提交回复
热议问题