[JavaScript] 모듈 내보내기 및 가져오기

모듈 다양하게 내보내기

선언부에 직접 export 사용하기

함수, 클래스, 변수 선언 앞에 export를 붙이면 해당 선언이 바로 외부에 공개됩니다.

// mathUtils.js
export function add(a, b) {
  return a + b;
}

export const PI = 3.1415926535;

export class Calculator {
  constructor() {
    this.value = 0;
  }
  add(num) {
    this.value += num;
    return this.value;
  }
}

선언 후 export 하기

함수를 먼저 선언한 후, 마지막에 export 구문으로 내보낼 수도 있습니다.

// stringUtils.js
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

function lowercase(str) {
  return str.toLowerCase();
}

export { capitalize, lowercase };

 default export

모듈이 단 하나의 기능이나 객체를 대표할 경우, export default를 사용할 수 있습니다. 그래서 파일당 하나만 있을 수 있습니다. default export는 가져올 때 중괄호를 사용하지 않고, 개발자가 원하는 이름으로 임포트할 수 있습니다.

// User.js
export default class User {
  constructor(name) {
    this.name = name;
  }
  sayHi() {
    return `Hi, ${this.name}!`;
  }
}

모듈을 가져오는 main.js 파일에서 User 클래스는 중괄호 없이 원하는 이름으로 가져올 수 있습니다.

// main.js
import User from './User.js';

const user = new User('Bob');
console.log(user.sayHi()); // "Hi, Bob!"

내보내기와 가져오기에서 이름 변경하기

내보낼 때 이름 변경하기

내보내기 시 기능을 내보낼 때 as 키워드를 사용하여 이름을 변경할 수 있습니다. 이는 모듈 자체 내에서 내보낸 이름을 변경하려는 경우에 유용합니다.

// utilities.js
function logInfo(message) {
  console.log(`Info: ${message}`);
}

function logError(message) {
  console.error(`Error: ${message}`);
}

// 두 함수를 각각 hi와 err로 내보냅니다.
export { logInfo as hi, logError as err };

utilities.js 모듈에서 logInfo 및 logError 함수는 as 키워드를 사용하여 각각 hi 및 err로 이름이 변경됩니다. 이제 모듈을 가져오는 모듈에서 이름이 변경된 이름을 사용하여 이러한 함수를 가져올 수 있습니다.

// app.js
import { hi, err } from './utilities.js'; // 이름이 변경된 이름으로 가져옵니다.

hi("Module system is cool!");   // Info: Module system is cool!
err("Something went wrong!");     // Error: Something went wrong

가져올 때 이름 변경하기

마찬가지로 기능을 가져올 때 as 키워드를 사용하여 이름을 변경할 수도 있습니다. 이는 가져오는 모듈에서 가져온 기능에 더 설명적인 이름을 지정하려는 경우에 유용합니다.

// formatter.js
export function formatDate(date) {
  return date.toISOString();
}

마찬가지로 기능을 가져올 때 as 키워드를 사용하여 이름을 변경할 수도 있습니다. 이는 가져오는 모듈에서 가져온 기능에 더 설명적인 이름을 지정하려는 경우에 유용합니다.

// main.js
// formatDate 함수를 dateFormatter라는 이름으로 가져오도록 이름 변경합니다.
import { formatDate as dateFormatter } from './formatter.js'; // 이름 변경된 이름으로 가져옵니다.

console.log(dateFormatter(new Date()));

모듈 재내보내기

모듈이 여러 파일로 나뉘어 있을 때, 한 파일에서 여러 모듈의 기능을 모아서 한꺼번에 내보낼 수 있습니다. 이를 재내보내기라고 하며, 모듈 인터페이스를 단순화하는 데 유용합니다.

// mathOperations.js
export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  return a / b;
}
// mathUtils.js
export function add(a, b) {
  return a + b;
}

export const PI = 3.1415926535;
// User.js
export default class User {
  constructor(name) {
    this.name = name;
  }
  sayHi() {
    return `Hi, ${this.name}!`;
  }
}

모든 이러한 기능을 별도의 파일에서 내보내는 대신 index.js 파일에서 진입점 모듈 역할을 하도록 하여 함께 재내보낼 수 있습니다.

// 📁 index.js (패키지 진입점)
export { add, PI } from './mathUtils.js'; // mathUtils.js에서 내보내기를 재내보냅니다.
export { multiply, divide } from './mathOperations.js'; // mathOperations.js에서 내보내기를 재내보냅니다.
export { default as User } from './User.js'; // User.js에서 기본 내보내기를 재내보냅니다.

이제 외부 모듈에서 index.js 모듈에서 모든 기능을 가져올 수 있으며, 기본 모듈에서 직접 가져온 것처럼 기능에 액세스할 수 있습니다.

// 📁 main.js
import { add, multiply, User } from './index.js'; // 진입점에서 기능 가져오기

console.log(add(3, 4));       // mathUtils.js의 add 함수 실행
console.log(multiply(5, 6));  // mathOperations.js의 multiply 함수 실행

const user = new User('Carol');
console.log(user.sayHi());