Destructuring assignment within import statements

2019-08-01 19:58发布

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.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-01 20:54

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-08-01 21:01

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')
查看更多
登录 后发表回答