I noticed that an ES6 destructuring import can be implemented like this:
foo.js
export default () => {
return {
a: 'b'
}
}
index.js
import foo from './foo';
export default foo;
export const bar = foo();
Then I can use the module with:
import foo, { bar } from 'my-module';
But when I use a "deep destructuring" import from my-module
, it fails with:
import foo, { bar: { a } } from 'my-module';
It seems like ES6 already implements the above syntax, but how do I use it?
The ImportClause of an import
isn't the same as destructuring. They do have some syntactic similarity, but if you read through the spec on import
, you can see that it never refers to the usual destructuring constructs such as DestructuringAssignmentTarget or BindingPattern.
Remember that imports create bindings between the modules, but destructuring assignments copy values from a source to a target. With your imagined destructuring import, if the value of bar
changes in the source module, would that change your imported a
? (After all, with import { bar } from 'my-module';
, if bar
changes in my-module
, the imported bar
reflects that change.) Or would the destructuring import copy the value of bar.a
to a
as of some point in time? And if so, what point in time?
You get the idea. They're just different beasts.
You can, of course import and then destructure:
import foo, { bar } from 'my-module';
let { a } = bar;
...but I'm sure you knew that. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With