JS - module


JS는 처음 만들어질 당시 스크립트의 크기가 크지 않았기 때문에 모듈 관련 문법이 없었다고 한다. 하지만 스크립트들의 크기가 커지기 시작하며 ES6에 표준으로 등록되었고, 이전에 Node.js 에서 주로 사용하던 방법은 CommonJS 이다.

모듈

모듈은 하나의 파일이라고 생각하면 된다. export, import 지시자를 사용하여 가져오거나 내보낼 수 있다.

// exportTest.js
export const person = (name, age) = {
  name,
  age
};

// importTest.js
import {person} = './exportTest.js';

console.log(person.name);

HTML에 스크립트를 태그 안에서 사용할 경우 type="module" 을 명시해줘야 한다.

또한 file:// 프로토콜로 열 경우 import, export 지시자는 동작하지 않는다! http, https 프로토콜에서만 동작한다.

모듈의 특징

  1. 엄격모드로 실행: 항상 use strict 로 실행된다.
  2. 모듈 단위 스코프: 각 모듈의 스코프는 다르다.
  3. 한 번만 실행된다: 여러 곳에서 호출하더라도 최초 호출 시 1번만 실행된다.
  4. import.meta: 모듈에 대한 정보를 확인 할 수 있다.
  5. this: 모듈의 최상위 this는 undefined 이다.
  6. 지연실행: 브라우저 환경에서 모듈은 지연 실행된다. defer 속성을 가진 것 처럼 동작

import, export

사용하는 방법은 크게 어렵지 않고 default 와 같이 사용하는 경우에만 주의를 좀 기울이면 되겠다.

// 내보낼 변수, 함수, 클래스 앞에 작성하기
export const months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

export class User {
  constructor(name) {
    this.name = name;
  }
}

// 한 번에 내보내기
const months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

class User {
  constructor(name) {
    this.name = name;
  }
}

export {months, User};

// 개별로 가져오기
import {months, User} from './test.js';
console.log(months, User);

// 한번에 가져오기
import * as sample from './test.js';
console.log(sample.months, sample.User);

// 내보내거나 가져올 데이터 이름 바꾸기
export {months as mon, User as person};
import {mon as months, person as User} from './test.js';

// default
export default class User {
  constructor(name) {
    this.name = name;
  }
}
import User from './test.js';
const person = new User('Aredra');

// default 지정하기
export const months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

export default class User {
  constructor(name) {
    this.name = name;
  }
}

import {default as User, months} from './test.js';

// 가져온 모듈 바로 내보내기
export {months} from './test.js';
export {default as User} from './test.js';

// default와 일반 export가 섞여 있을 때
export * from './test.js'; // named export를 다시 내보내기
export {default} from './test.js'; // default export를 다시 내보내기

동적 import

import() 를 사용하여 모듈이 내보내는 것들을 모두 포함하는 객체를 담은 Promise 를 반환 받을 수 있다.

// say.js
export function hi() {
  alert(`안녕하세요.`);
}

export function bye() {
  alert(`안녕히 가세요.`);
}

export default function() {
  alert("export default한 모듈을 불러왔습니다!");
}

// import.js
let {hi, bye} = await import('./say.js');

hi();
bye();

// import default.js
let {default: customAlert} = await import('./say.js'); 
customAlert();

출처

모던 JavaScript 튜토리얼

Tags:

Categories:

Updated: