Import statements & destructuring

Isiah Meadows isiahmeadows at gmail.com
Fri Oct 16 06:34:11 UTC 2015


The reason you can't destructure directly in the import statement is
because of the static syntax for named imports, such as `import {foo}
from "bar";`. That is determined at compile time, and the linking
itself is done at compile time. There's nothing stopping you from
doing this, though:

```js
import config from "./config";
const {api: {host}} = config;

doSomething(host);
```

On Thu, Oct 15, 2015 at 11:01 AM, PLIQUE Guillaume
<guillaumeplique at gmail.com> wrote:
> Considering the following file exporting a raw object:
>
> ```js
> /* ./config.js */
> const config = {
>   api: {
>     port: 25,
>     host: 'localhost'
>   }
> };
>
> export default config;
> ```
>
> If another file wants to import this file in order to access the
> api.host property, it could do it thusly:
>
> ```js
> import config from './config';
> console.log(config.api.host);
>
> // or else (typically this is what one would expect when importing
> some older modules through Babel)
> // but I am not entirely sure this would work for real with ES2015
> import {api} from './config';
> console.log(api.host);
> ```
>
> Therefore, wouldn't it be useful to be able to use destructuring
> within import statement as you would with objects:
>
> ```js
> import {api: {host}} from './config';
> console.log(host);
> ```
>
> I guess this does not work for static evaluation reasons but I just
> want to be sure this is it or if there are more obvious/profound
> reasons concerning modules' system, syntax or philosophy that prevent
> this.
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Isiah Meadows


More information about the es-discuss mailing list