JavaScript의 모듈 시스템 (ES6 Modules) 에서 export와 import는 코드의 재사용성과 유지보수성을 높이는 중요한 기능입니다.
이를 통해 하나의 파일에서 정의한 변수, 함수, 클래스 등을 다른 파일에서도 사용할 수 있습니다.
1. export의 종류
JavaScript에서는 두 가지 방식으로 모듈을 내보낼 수 있습니다.
(1) Named Export (이름을 지정한 내보내기)
Named Export는 하나의 파일에서 여러 개의 변수, 함수, 클래스를 개별적으로 내보낼 수 있는 방식입니다.
사용법
// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
이렇게 export하면 다른 파일에서 선택적으로 가져올 수 있습니다.
가져오기 (import)
// main.js
import { add, subtract } from "./utils.js";
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
✔ {}를 사용하여 특정 항목만 가져올 수 있음.
✔ import { 함수명 }과 같이 이름을 정확히 일치시켜야 함.
(2) Default Export (기본 내보내기)
Default Export는 파일당 하나의 모듈만 내보낼 때 사용합니다.
파일에서 export default로 지정된 값은 가져올 때 이름을 변경해서 사용할 수도 있습니다.
사용법
// math.js
const divide = (a, b) => a / b;
export default divide;
가져오기 (import)
// main.js
import divide from "./math.js"; // 이름 변경 가능
console.log(divide(10, 2)); // 5
✔ export default는 {} 없이 가져옴.
✔ import divide에서 이름을 변경하여 가져와도 문제없음.
2. export와 import 혼합 사용
Named Export와 Default Export를 동시에 사용할 수도 있습니다.
// utils.js
export const square = (x) => x * x;
export const cube = (x) => x * x * x;
const pow = (base, exponent) => Math.pow(base, exponent);
export default pow;
// main.js
import pow, { square, cube } from "./utils.js";
console.log(pow(2, 3)); // 8
console.log(square(3)); // 9
console.log(cube(2)); // 8
✔ pow는 export default이므로 {} 없이 가져옴
✔ square와 cube는 Named Export이므로 {} 안에 넣어 가져옴
3. 모든 Named Export 한 번에 가져오기 (import * as ...)
만약 Named Export가 많은 경우, *을 사용하여 모든 내보낸 항목을 가져올 수도 있습니다.
사용법
// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
// main.js
import * as math from "./utils.js";
console.log(math.add(5, 3)); // 8
console.log(math.subtract(5, 3)); // 2
console.log(math.multiply(5, 3)); // 15
✔ 모든 함수를 한 번에 가져올 수 있음
✔ math.add(), math.subtract()처럼 네임스페이스를 붙여 사용
4. export와 import의 활용 예시
React에서 export 사용 예시
// components/Button.js
export const Button = ({ label }) => {
return <button>{label}</button>;
};
export default function PrimaryButton({ label }) {
return <button style={{ background: "blue", color: "white" }}>{label}</button>;
}
// App.js
import PrimaryButton, { Button } from "./components/Button";
function App() {
return (
<div>
<Button label="Click me" />
<PrimaryButton label="Primary Click" />
</div>
);
}
✔ PrimaryButton은 export default로 내보냈기 때문에 {} 없이 가져옴
✔ Button은 Named Export라 {} 안에 넣어서 가져옴
5. 정리
| 여러 개의 항목을 내보낼 때 | ✅ 적합 | ❌ 부적합 |
| 하나의 함수/클래스를 내보낼 때 | ❌ 부적합 | ✅ 적합 |
| 가져오는 이름 변경 | ❌ 불가능 | ✅ 가능 |
| 모듈 하나만 가져올 때 | ❌ 불편 | ✅ 편리 |
✔ 여러 개의 함수/변수를 내보낼 때 → Named Export (export { func1, func2 })
✔ 파일에서 하나의 기본 기능만 내보낼 때 → Default Export (export default)
✔ 가져오는 이름을 유지해야 하면 → Named Export
✔ 이름을 변경해서 사용하고 싶다면 → Default Export
'Category > JavaScript' 카테고리의 다른 글
| 원시값(Primitive)과 객체의 차이 (0) | 2025.03.20 |
|---|---|
| ... (Spread Operator)로 얕은 복사(Shallow Copy)하기 (0) | 2025.03.18 |
| Axios: HTTP 요청을 쉽게 만드는 JavaScript 라이브러리 (3) | 2024.11.11 |
| [JavaScript] 브라우저의 기본 동작 막기 event.preventDefault() (1) | 2024.11.07 |
| 자바스크립트 reduce() (1) | 2024.10.29 |