Dot notation in React imports

Caciano :

I have been seeing many react frameworks recommend dot notation while importing.
e.g. instead of

import Y from 'X/Y';  
<Y />  

they would use:

import X from 'X';  
<X.Y />

From what I've tested, they both work.
My question is what, if any, are the differences?
Especially if, lets say, you only need to use Y, will the second notation import unnecessary data since you don't need X? Would you only use the second notation in cases when you would use both X and Y, and not just Y?

Alex Wayne :

These are not identical, but they may sometimes have an identical result.

import Y from 'X/Y'

This says import the file at path X/Y and store the default export as the local constant Y. X may be an installed npm module, in which case you're drilling into its directory structure to find a particular file.

import X from 'X'

This says import the file at path X and store the default export as the local constant X. It's importing a different file entirely.

Now, if X is something like:

import Y from './Y'
export default {
  other: { stuff: true },
  Y,
}

Then you could access X.Y easily. But there is no guarantee that it's implemented that way.

When you import a module without drilling into it, you are import the structure that the module author intended to expose. This may be quite different from the directory structure of the implementation of the module. In theory, an internal refactoring that doesn't change the exported interface at all could break your code if you import it's internal files.

This is why you should follow a module's directions about how to import it.


Now let's say this was your module:

export const Y = 'I am Y'
export default 'I am the default export of X'

Then you can import this like so:

import X from 'X'   // X === 'I am the default export of X'
import {Y} from 'X' // Y === 'I am Y' 

console.log(X.Y)    // undefined. Y is not a property of the default export.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7213&siteId=1