Javascript - Module(export, import)
module
거대한 코드들이 작은 파일로 나눠질 수 있도록 한다.
모듈 덕분에 import, export 를 할 수 있게된다.
- Dynamic Module : 어플리케이션 로딩이 빨라진다.
Named Exports
파일 혹은 모듈이 원하는 만큼 많은 수의 Named Exports 를 가질 수 있다.
// 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 {plus} from "./math";
import 하고 싶은 함수의 이름을 중괄호({}) 안에 쓰면된다.
여기서 중요한 점은 반드시 export 된 이름과 import 할 이름이 같아야된다는 것이다.
만약 함수 명을 바꾸고 싶을 때는 as 를 사용하면 된다.
import {plus as add} from "./math";
add(2, 2);
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);
Default export 는 우리가 원하는 이름으로 import 가 가능하다.
import myMath from "./math";
math.plus(2, 2);
파일 내에 모든 함수들이 들어있는 객체를 원하는 이름으로 import 할 수 있다.
단 한개의 함수만 export 하고 싶을 때 사용하면 좋다.
// math.js
const plus = (a, b) => a+b;
export default plus;
// main.js
import plus from "./math";
plus(2, 2);
만약 Default export 와 named export 가 섞여 있는 경우에는 아래와 같이 import 가 가능하디.
// db.js
const connectionToDB = () => {/*code*/}
export const getUrl = () => {/*code*/}
export default connectionToDB;
import connect, {getUrl} from "./db";
* : star import
export 된 모든 내용을 import 하고 싶을 때 사용한다.
단, default 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.minus(5, 2);
- ' * ' : math 함수에서 export 된 모든 것을 import 해서 myMath 라는 객체에 넣는다는 뜻이다.
Dynamic import
보통 import 방식은 파일의 위에서부터 전부, 모든걸 import 한다.
이는 로딩 속도를 늦추는 원인 중 하나가 될 수도 있다.
왜냐하면 유저가 사용하든 말든 웹 사이트의 모든 코드를 전부 다운로드 해야되기 때문이다.
Dynamic import 를 사용하면 실제로 유저가 사용할 모듈만 import 할 수가 있다.
function doMath() {
import("./math")
.then(math => math.plus(2, 2));
}
btn.addEventListener("click", doMath);
위와 같이 요청이 있을 때마다 모듈을 로딩하게 된다.async/await
를 사용하면 코드를 더 좋게 만들 수 있다.
async function doMath() {
const math = await import("./math");
math.plus(2, 2);
}
btn.addEventListener("click", doMath);