Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use deep destructuring on imports in ES6 syntax?

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?

like image 851
E_Jovi Avatar asked Dec 14 '16 08:12

E_Jovi


1 Answers

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. :-)

like image 124
T.J. Crowder Avatar answered Oct 16 '22 17:10

T.J. Crowder