본문 바로가기
프로그래밍 언어/Javascript

[Javascript] export와 export default 차이

by 스코필 2025. 2. 20.

📝 한 눈으로 정리

특징 export (Named Export) export default (Default Export)
내보낼 개수 여러 개 가능 하나만 가능
가져올 때 중괄호 {} 필요함 필요 없음
가져올 때 이름 변경 as 키워드 필요 자유롭게 변경 가능

 

export (Named Export) 의 특징

  1. 여러 개의 값을 내보낼 수 있다.
  2. 내보낸 값은 이름을 기준으로 가져와야한다.
  3. {} 사용하여 필요한 값만 가져올 수 있다.

사용법

// export.js
export const add = (x, y) => x + y;
export const subtract = (x, y) => x - y;
// index.js
import { add } from "./export.js";

console.log(add(1, 2))  // 3

 

{} 안에 내보낸 이름을 정확히 일치시켜야 한다.

이름을 변경하고 싶다면, as키워드를 사용한다.

import { add as sum } from './export.js';
console.log(sum(2, 3));	// 3

 

export default ( Default Export ) 의 특징

1. 모듈당 하나의 값만 기본으로 내보낼 수 있다. (하지만 내보내는 값이 객체라면 여러 개의 값을 포함할 수 있다.)

2. 가져올 때 이름을 자유롭게 정할 수 있다.

3. {} 없이 import 가능하다.

사용법

// exportDefault.js
export default {
  add(x, y) {
    return x + y
  },

  minus(x, y) {
    return x - y
  }
}
// main.js
import changeName from "./exportDefault.js"

console.log(changeName.add(1, 2))	// 3
console.log(changeName.subtract(5, 3))	// 2

 

export deault의 값을 객체로 사용할 경우

//exportDefault2.js
const add = (x, y) => x + y;
const minus = (x, y) => x - y;

export default { add, minus };
//main.js
import calculate from "./exportDefault2.js"

console.log(calculate.add(3, 2))  // 5
console.log(calculate.subtract(2, 1)) // 1

 

결론

여러 개의 값을 내보낼 때, export가 적합하다.

파일에서 하나의 값을 내보낼 때, export default가 적합하다.

'프로그래밍 언어 > Javascript' 카테고리의 다른 글

[Javascript] indexOf() 메서드  (1) 2025.02.13