ES Modules

Hanji·2021년 12월 4일
0
post-thumbnail

니꼬쌤의 ES Modules 강의 내용을 정리한 페이지입니다.
영상이 7분 안되니 강의 보시는 걸 추천해요.🧚‍♀️
니콜라스쌤의 유튜브 강의👍

Named Exports

  • 많은 것들을 export / import 하고 싶을 때 사용

ex)

// 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된 이름과 같아야 한다.

위의 예시에서 plus 대신 add로 import하여 사용할 수 없음.

// main.js
import { add } from './math'; // 🙅‍♀️

만약 plus를 add로 이름을 바꾸고 싶다면 as를 사용해서 바꾸면 사용 가능.

import {plus as add} from './math'; // 🙆‍♀️

add(2,2);

Default Exports

각 파일마다 단 한개만 존재. -> import 하기 더 간단함.

// db.js
const connectToDB = () => {/*magic*/};
export default connectToDB;

//main.js
import connect from './db';

→ 한개의 파일에서 모든걸 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);

named export와 달리 원하는 이름으로 변경 가능

ex)

import myMath from './math';

myMath.plus(2,2);

✍️named exports와 default exports가 섞여있는 경우

//db.js
const connectToDB = () => {/*magic*/};
export const getUrl = () => {/*magic*/};
export default connectToDB;

//main.js
import connect, {getUrl} from './db';

Star Import (*)

  • 모든 exported된 내용을 import 하고 싶을 때
// 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);
myMath.minus(2,2);

🔥 로딩을 빠르게 하는 방법

  1. 필요한 것만 import 하기
    → 예제의 math.js 사용 시 named export로 사용하는게 나음.
  2. Dynamic Import 사용하기

🤔 Dynamic Import?

import 방식은 파일의 위에서부터 모든걸 import 함.
유저가 사용하든 안하든 웹사이트의 모든 코드를 몽땅 다운로드 하므로 로딩 느려짐.
→ Dynamic Import를 사용하여 실제 유저가 사용할 모듈만 import하기

ex)

async function doMath() {
	const math = await import('./math');
    math.plus(2,2);
}

btn.addEventListener('click', doMath);

→ 유저가 버튼 클릭할때마다 모듈 로딩.

0개의 댓글