JS 모듈: export(내보내기)와 import(가져오기)

ES6에서 JavaScript에서는 모듈을 지원합니다. 모듈 구성하고 이용하면 파일 간의 코드를 쉽게 공유할 수 있으며, 코드의 가독성과 유지보수성을 높일 수 있습니다. 모듈 시스템에서는 import와 export 키워드를 사용하여 모듈을 로드하고 내보낼 수 있습니다.

 

import와 export는 컴파일 시점에서 결정되며, import 선언과 export선언은 호이스팅되어 최상위에 위치됩니다.

 

export: 내보내기

모듈에서 외부로 내보내기 위한 키워드입니다. 이를 이용하여 아래와 같이 변수, 함수, 클래스, 객체 등을 내보낼 수 있습니다.

// 변수 내보내기
export const value = 25;

// 여러 값 내보내기
const z = 'first';
const y = 'second';
export {z as x, y};          // 이름을 변경할 수 있습니다.

// 함수 내보내기
export function add(a, b) {
	return a + b;
}

// 클래스 내보내기
export class Person {
	constructor(name, age) {
    	this.name = name;
        this.age = age;
    }
    
    introduce() {
    	console.log(`my name is ${this.name}`);
    }
}

// 기본(default) 내보내기와 명명 내보내기
export default function nextYear(user) {
	console.log(`current user's age: ${user.age}`);
    Year++;
}
export let Year = 2023;

 

 

import: 가져오기

모듈에서 외부 모듈을 가져오기 위해 키워드입니다. export된 변수, 함수, 클래스, 객체 등을 가져올 수 있습니다.

기본(default) 가져오기는 기본 내보내기(default export)에서 사용한 이름과 일치하지 않아도 됩니다.

// 변수 가져오기
import { value } from './module';

// 함수 가져오기
import { add } from './module';

// 클래스 가져오기
import { Person } from './module';

// 전부 가져오기
import * from './module';

import { Year as nextYear } from './module'; // 이름을 변경할 수 있습니다.