JavaScript

[Javascript] ECMA Script6 export와 import 정리

반응형

Named Export

// math.js
export const plus = (a, b) => a + b;
export const minus = (a, b) => a - b;
export const divide = (a, b) => a / b;

위와 같이 각 함수를 export를 하면

import { plus } from "./math";

이렇게 괄호로 감싸서 원하는 함수를 import 해올 수 있습니다.

 

여기서 주의할 점은 export한 파일의 함수이름과 import하는 폴더의 괄호안에 이름이 같아야 한다는 점입니다.

 

여기서 이름을 바꾸고자 한다면 다음과 같이 변경하고 사용할 수 있습니다.

//main.js
import { plus as add } from "./math";

add(2, 2);

 

Default Export

default export는 하나의 파일에 하나만 존재해야 합니다.

 

이렇게 하나의 파일에서 모든걸 export하고 다른 파일에서 모든걸 import하는 방식이 있긴합니다.

 

// math.js
const plus = (a, b) => a + b;
const minus = (a, b) => a - b;
const divide = (a, b) => a / b;
export default { plus, minus, divide }

 

// main.js
import math from "./math";

math.plus(2, 2);

이렇게 math라는 이름으로 전부 import 할 수 있습니다.

 

눈치 채셨겠지만 named export와 다르게 이름을 바꿔서 가져올 수 있고 괄호도 들어가지 않습니다.

 

// db.js
const connectToDB = () => {.....}

export default connectToDB
// main.js
import connect from "./db";

이처럼 딱 하나의 함수를 가져오고 싶을 때 이 함수를 export default 하고 다른 이름으로 가져오는 방법도 있습니다.

 

또한, 아래와 같이 named export 와 default export 를 한 줄에 섞을 수 도 있습니다.

// db.js
const connectToDB = () => { ..... };
export const getUrl = () => { ..... };
export default connectToDB;
// main.js
import connect, { getUrl } from "./db";

 

모든 exported 된 내용을 import 하고 싶을 때 '*' 를 사용할 수 있습니다.

단, defualt export 가 없는 파일에서 사용할 수 있습니다.

 

 

// math.js
export const plus = (a, b) => a + b;
export const minus = (a, b) => a - b;
export const divide = (a, b) => a / b;
// main.js
import * as myMath from "./math";
myMath.plus(2, 2);

이렇게 math.js의 모든 함수를 import 해서 myMath라는 변수로 가져오겠다는 뜻입니다.

 

이런 과정속에서 빠르게 import 하고자 한다면 어떻게 해야할까?

 

필요한 것만 import 하도록 합니다.

 

예를 들면 Math 모듈에서는 default export 로 전부 가져오는 것 보다 named export 로 필요한 것을 가져와 사용하는 것이 좋습니다.

 

Dynamic import

실제 유저가 사용할 모듈만 import 할 수 있습니다.

 

function doMath() {
  import("./math")
  .then(math => math.plus(2, 2))
}
btn.addEvencListener("click", doMath)

이렇게 코드를 작성하면 click할 때만 모듈을 import 하게 됩니다.

 

 

async await 으로 다음과 같이 만들 수 도 있습니다.

async function doMath() {
  const math = await import("./math");
  math.plus(2, 2);
}
btn.addEvencListener("click", doMath)

 

다음 노마드코더의 영상을 보고 정리하고자 포스팅했습니다. 

 

https://www.youtube.com/watch?v=WUirHxOBXL4 

 

반응형