Home > Software design >  I don't understand why export like this in React
I don't understand why export like this in React

Time:04-13

I found many files were exported like this, but I don't understand why these were exported this way. Are there any advantages or reasons?

index.ts

export { default } from './Something'

Something.tsx

cosnt _Something= () => {
 some codes....
}

cosnt Something = memo(_Something)

export default Something

These two tsx file exist same directory.

CodePudding user response:

You're looking for default export and named exports.

in export default Something case, you can use it with import Something from 'path'. So you only want to export one thing. It can be used as a namespace also. It equals export { myFunction as default };

in export { Something } case, you can use it with import { Something } from 'path'. You can export many things with names. It increases the readability. For sure, you can also import { Something as Another} from 'path'.

These two appoarches are not conflict. But only one default can be assigned.

// index.ts
export default function Something(){
}
export const CONST_A = 'A'
export const CONST_B = 'B'

// use.ts
import { default as Something, CONST_A, CONST_B} from './index.ts'

CodePudding user response:

Its just a pattern, instead of importing exact paths:

import Nav from 'components/Nav.react';
import Tooltip from 'components/Tooltip.react';

Sometimes you want a merge:

import { Nav, Tooltip } from 'components';

It requires exports from index file located at the target folder ('components' in this case):

// src/components/index.ts

export * from './Nav.react';
export * from './Tooltip.react';

// Or
export { Nav } from './Nav.react'; // Has a named export
export { default as Tooltip } from './Tooltip.react'; // Has default export

See more context in other question How to intellisense alias module path in VSCode.

  • Related