default export VS named export

이연중·2021년 9월 28일
0

TypeScript

목록 보기
3/4

Default Export


  • default export로 선언된 모듈은 하나의 파일 안에서 하나의 변수 또는 클래스 etc...만을 export 할 수 있다.
  • import 할 때의 네이밍이 자유롭다.
  • var, let, const를 동시에 사용해 export 할 수는 없다.
//errorPet.ts
export default const errorPet= "//error"

//pet.ts
export default class pet{}

//dog.ts
import pet from "./pet"

//cat.ts
import myLittleCat from "./pet"

Additional
default export는 named default에 default가 붙은 것이다.
그렇기에 한 파일 내에 default export가 존재하면 다음과 같이 export 할 수도 있다.

import { default as petDog } from "./pet"

named export


  • export로 선언된 모듈은 한 파일 내에서 여러 변수나 클래스 또는 etc...를 export할 수 있다.
  • import 시에는 named export로 선언된 이름과 동일하게 해야한다.(네이밍을 하고싶으면 as 키워드를 사용해야 한다.)
//pet.ts
export class pet{}

//dog.ts
import { dog } from "./pet" //error export에서 정의한 것과 동일한 이름을 사용해야 함

//cat.ts
import { pet } from "./pet"

//pig.ts
import { pet as pig } from "./pet"

//animal.ts
import * as animal from "./pet"

결론


TypeScript에서 프로젝트 코드 내에서 작업할 때 default export 대신 named export를 더 선호한다.
그 이유는 리팩토링하기에 더 수월하기 때문이다.
default export를 사용해 네이밍을 자유롭게 하는 것은 개발의 유연성을 제공하지만, 리팩토링 작업을 할 때 번거로울 수 있다.
반면, named export는 그 부분이 통일되어있기 때문에 리팩토링 작업 시 이점이 있다.

한개의 파일에 하나의 함수형 컴포넌트 또는 클래스만 있다면, default export를 사용하는 것이 당연해보이지만, 이는 개발자나 팀마다 다른것 같다.

참고

https://stackoverflow.com/questions/33305954/typescript-export-vs-default-export
https://medium.com/@_diana_lee/default-export%EC%99%80-named-export-%EC%B0%A8%EC%9D%B4%EC%A0%90-38fa5d7f57d4

profile
Always's Archives

0개의 댓글