Friday, May 17, 2024
199
rated 0 times [  200] [ 1]  / answers: 1 / hits: 60794  / 9 Years ago, wed, november 4, 2015, 12:00:00

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.)


More From » ecmascript-6

 Answers
63
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.


[#64505] Monday, November 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;