Can I destructure a default export object on import?
Given the following export syntax (export default
)
const foo = ...
function bar() { ... }
export default { foo, bar };
is the following import syntax valid JS?
import { foo, bar } from './export-file';
I ask because it DOES work on my system, but I've been told it should NOT work according to the spec.
No. You can only destructure an object after importing it into a variable.
Notice that imports/exports have syntax and semantics that are completely different from those of object literals / object patterns. The only common thing is that both use curly braces, and their shorthand representations (with only identifier names and commas) are indistinguishable.
Yes. It does import two named exports from the module. It's a shorthand notation for
which means "declare a binding
foo
and let it reference the variable that was exported under the namefoo
fromexport-file
, and declare a bindingbar
and let it reference the variable that was exported under the namebar
fromexport-file
".No. What it does is to declare an invisible variable, initialise it with the object
{ foo: foo, bar: bar }
, and export it under the namedefault
.When this module is imported as
export-file
, the namedefault
will not be used and the namesfoo
andbar
will not be found which leads to aSyntaxError
.To fix this, you either need to import the default-exported object:
Or you keep your import syntax and instead use named exports: