[React] export, export default 간단 정리

VD·2023년 1월 9일
1

혼자공부하기

목록 보기
1/1
post-thumbnail

리액트에서 함수 표현식과 선언식 중 뭘 써야되는지 궁금해서 검색하던 중

export default라는 것을 봤다. 나는 맨땅에 해딩중인 독학러이기 때문에 모든 것에 ?가 생기기 마련dlek. 그래서 함수 선언식, 표현식보다 export default에 대해서 먼저 알아봤다.

export vs export default

export default는 쉽게 이해하자면 일반적으로 해당 모듈엔 하나의 개체(변수, 클래스, 함수 등)만 있다는 것이다.

test.js
function test1() {
    console.log('export default test1()')
}
function test2() {
    console.log('export default test2()')
}
export default test1
export default test2 // test1에만 있을 경우엔 정상적으로 작동된다.

위 코드를 그대로 복붙해보면 알겠지만 export default test2 때문에 에러가 발생한다.
해결방법은 당연하게 export default를 하나만 쓰면 된다.

test.js
function test1() {
    console.log('export default test1()')
}

export default test1

App.js
import test1 from '경로'

아래 이미지는 위 코드의 결과 이미지다

export는 여러 개체가 있는 모듈에서 내보낼 때 사용한다. 그리고 특정 개체만 따로 내보내는 것도 가능하다.

test.js
function test1() {
    console.log('export default test1()')
}
export {test1}

App.js
import {test1} from '경로'

여러개를 export할 때는

test.js
function test1() {
    console.log('export default test1()')
}
function test2() {
    console.log('export default test2()')
}

export {test1, test2}

App.js
import {test1, test2} from '경로'

이렇게 하면 여러개를 내보내고 불러올 수 있다.

export할 때도 하나씩 불러올 수 있지만 {···}이라는 디테일한 문법 차이가 있다.

import {test1} from '경로'
profile
코딩을 합시다

0개의 댓글