Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Destructuring and Module imports

I was under the impression that this syntax:

import Router from 'react-router'; var {Link} = Router; 

has the same final result as this:

import {Link} from 'react-router'; 

Can someone explain what the difference is?

(I originally thought it was a React Router Bug.)

like image 569
Guy Avatar asked Nov 04 '15 14:11

Guy


People also ask

What is import in ES6?

Introduction to ES6 import:The import statement is used to import modules that are exported by some other module. A module is a file that contains a piece of reusable code. The import modules are in strict mode whether it is declared or not.

What is ES6 Destructuring?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

What is advantage of Destructuring in JavaScript?

Advantages of Destructuring:It makes developer's life easy, by assigning their own variables. Nested data is more complex, it takes time to access, but by the use of destructuring, we can access faster of nested data.


1 Answers

import {Link} from 'react-router'; 

imports a named export from react-router, i.e. something like

export const Link = 42; 

import Router from 'react-router'; const {Link} = Router; 

pulls out the property Link from the default export, assuming it is an object, e.g.

export default {   Link: 42 }; 

(the default export is actually nothing but a standardized named export with the name "default").

See also export on MDN.

Complete example:

// react-router.js export const Link = 42; export default {   Link: 21, };   // something.js import {Link} from './react-router'; import Router from './react-router'; const {Link: Link2} = Router;  console.log(Link); // 42 console.log(Link2); // 21 

With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS. But those are two different constructs as far as the language goes.

like image 135
Felix Kling Avatar answered Sep 28 '22 09:09

Felix Kling