Javascript/Typescript

[Javascript] 클래스 export/import 하기

범데이 2022. 7. 10. 22:32

1. 개요

Javascript에서 클래스를 import/export를 하기 위해선 어떻게 하는지 찾아보던 도중,

영어로 된 좋은 포스팅을 찾게 되었고, 해당 포스팅을 한글로 번역하여 정리하였다. (해당 사이트: 새창)

 

 


2. Export

named export를 사용하여 export class Employee {} 와 같이 Javascript에서 클래스를 내보내보자.

내보낸 클래스는 named import를 사용하여 import {Employee} from './another-file.js'와 같이 가져올 수 있다.

 

얼마든지 이와같이 파일에서 필요에 따라 이름을 지정하여 쓸수 있다.

 

다음은 'another-file.js' 라는 파일에서 클래스를 내보내는 예이다.

 

[another-file.js]

// 👇️ named export
export class Employee {
  constructor(id, name, salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
  }

  increaseSalary() {
    this.salary += 100;
  }
}

클래스의 정의와 동일한 줄에서 export를 사용하는 것은 클래스를 정의한 후에 클래스를 객체로 export하는 것과 같다.

 

[another-file.js]

class Employee {
  constructor(id, name, salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
  }

  increaseSalary() {
    this.salary += 100;
  }
}

// 👇️ named export (same as previous code snippet)
export {Employee};

 

3. Import

다음은 'index.js'라는 파일에서 해당 클래스를 어떻게 import하는지 살펴보자.

 

[index.js]

import {Employee} from './another-file.js';

const emp = new Employee(1, 'Alice', 100);

console.log(emp.id); // 👉️ 1
console.log(emp.name); // 👉️ "Alice"

emp.increaseSalary();

console.log(emp.salary); // 👉️ 200

필요한 경우 'another-file.js' 파일을 가리키는 경로를 수정해야 한다.

(위의 예제에서는 'another-file.js'와 'index.js'파일이 같은 디렉터리에 있다고 가정한다.)

 

예를 들어, import하고자 하는 파일이 한단계 상위에 있으면, 다음과 같이 import를 해야한다.

import {Employee} from '../another-file.js'.

 

위에서 우리는 클래스를 가져올 때 이름을 중괄호로 묶었다. 이것을 named import라고 부른다.

 

import/export 구문은 Javascript에서 ES6 모듈이라고 한다.

 

 

4. Named export/import & Default expot/import

다른 파일에서 클래스를 가져오려면 named export 또는 default export를 사용하여 내보내야 한다.

위의 예에서는 named exportnamed import를 사용하였다.

 

 

named export와 default export의 주된 차이점은 파일 당 여러 named export를 할 수 있으나, default export는 하나만 가질 수 있다는 것이다.

(만약 아래와 같이 한 파일에서 여러 default export를 사용한다면, error가 발생한다.)

 

[another-file.js]

// 👇️ 2 default exports in same file = error
export default class Employee {
  constructor(id, name, salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
  }

  increaseSalary() {
    this.salary += 100;
  }
}

// ⛔️ SyntaxError: Duplicate export of 'default'
export default class Person {}

 

 

중요: 만약 default export로 변수(혹은 화살표 함수)를 내보낸다면, 한 줄에 선언하고 다음 줄에 내보내야 한다. 같은 줄에서 변수를 선언하고 default export를 할 수 없다.

 

언급 하였듯이, 단일 파일에서는 하나의 default export와 필요한 만큼의 named export를 사용할 수 있다.

 

다음은 두가지를 모두 사용한 사례이다.(defaultnamed export들)

 

[another-file.js]

// 👇️ default export
export default class Employee {
  constructor(id, name, salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
  }

  increaseSalary() {
    this.salary += 100;
  }
}

// 👇️ named export
export class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

 

그리고 그 두개의 클래스들을 어떻게 import하는지 보자.

 

[index.js]

// 👇️ default and named imports
import Employee, {Person} from './another-file.js';

const emp = new Employee(1, 'Alice', 100);

console.log(emp.id); // 👉️ 1
console.log(emp.name); // 👉️ "Alice"

const person = new Person('Bob', 30);

console.log(person.name); // 👉️ "Bob"

 

default import는 중괄호로 묶지 않는다.

 

'Employee' 클래스를 가져오기 위해 default import를 사용하였고, 'Person' 클래스를 가져오기 위해 named import를 사용하였다.

 

경험상 대부분의 실제 코드베이스는 자동 완성 및 자동 가져오기를 위해 IDE를 더 쉽게 활용할 수 있도록 하기 때문에 named export/import를 독점적으로 사용한다.

또한 어떤 membersdefault export또는 named export로 내보낼지 생각할 필요가 없다.

 

 

 


#Reference

https://bobbyhadz.com/blog/javascript-export-class

 

반응형