简体   繁体   English

如何在ES6语法中对导入进行深度解构?

[英]How to use deep destructuring on imports in ES6 syntax?

I noticed that an ES6 destructuring import can be implemented like this: 我注意到ES6解构导入可以像这样实现:

foo.js foo.js

export default () => {
  return {
    a: 'b'
  }
}

index.js 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: 但是当我从my-module使用“深度解构”导入时,它失败了:

import foo, { bar: { a } } from 'my-module';

It seems like ES6 already implements the above syntax, but how do I use it? 似乎ES6已经实现了上述语法,但我该如何使用它?

The ImportClause of an import isn't the same as destructuring. importImportClause与解构不同。 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 . 它们确实有一些语法相似性,但是如果你阅读import规范 ,你会发现它从不引用通常的解构结构,如DestructuringAssignmentTargetBindingPattern

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 ? 用你想象的解构导入,如果源模块中bar的值发生变化,那会改变你导入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? (毕竟, import { bar } from 'my-module';如果bar在改变my-module ,导入bar反映这一变化。)或者将解构进口的值复制bar.a ,以a为一些时间点? 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. ......但我相信你知道的。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM