Import statements & destructuring

# PLIQUE Guillaume (9 years ago)

Considering the following file exporting a raw object:

/* ./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:

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:

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.

# Isiah Meadows (9 years ago)

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:

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

doSomething(host);