Can I destructure a default export object on import?
Given the following export syntax (export default)
const foo = ...
function bar()
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);
})();
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');