Destructuring assignment within import statements

你离开我真会死。 提交于 2019-12-24 08:25:35

问题


According to this source and a vague memory of having seen this sort of usage in a project somewhere, I'm curious if anyone has been able to do the following:

import {map: { series }} from 'contra'

As stated on this destructuring assignment overview:

The import statement in ES6 behaves similarly to destructuring, but it is important to note that it is not actually destructuring.

It appears that imports work a little different and perhaps one cannot expect the same exact behavior, but I haven't been able to verify the status of this. Is what I am trying to do part of the official ECMAScript 6/7 spec?

In attempting to answer this, please kindly include (or link) the portion of the spec that clarifies this concern.


回答1:


The relevant portion of the spec is here.

An ImportDeclaration is

import ImportClause FromClause;

If you examine ImportClause, you'll see it's just the familiar * as Foo, or DefaultImport, or {ImportSpecifier, ...}, etc., where ImportSpecifier is an ImportBinding, which in turn is a BindingIdentifer, which is just a plain old Identifier.

The MDN entry is somewhere between misleading and completely wrong. It should have said (and now does say):

The import statement in ES6 has a superficial resemblance to destructuring, but is actually completely unrelated.

I find more and more incorrect and misleading information in MDN these days. It should be taken with a grain of salt. The authoritative reference is the spec.




回答2:


You can use destructuring assignment only when you're assigning variables. Imports are completely different thing and you can't use destructuring assignment with them.

You can instead use destructuring assignment with a direct require() call (assuming that you're using Node.js or RequireJS):

const {map: { series }} = require('contra')


来源:https://stackoverflow.com/questions/39376073/destructuring-assignment-within-import-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!