[ES6] Import / Export

sujinΒ·2021λ…„ 12μ›” 30일
0

ES6

λͺ©λ‘ 보기
1/4
post-thumbnail

πŸ“ λͺ¨λ“ˆ : νŒŒμΌμ„ μͺΌκ°œμ„œ λ³΄κ΄€ν•¨μœΌλ‘œμ¨ μ½”λ“œμ˜ μž¬ν™œμš©μ„±κ³Ό μœ μ§€λ³΄μˆ˜λ₯Ό μ‰½κ²Œ ν•  수 μžˆλ„λ‘ ν•œλ‹€.


1. Named Export

  • 파일 ν˜Ήμ€ λͺ¨λ“ˆμ΄ μ›ν•˜λŠ” 만큼 λ§Žμ€ 수의 named exportλ₯Ό κ°€μ§ˆ 수 있음
  • μ€‘κ΄„ν˜Έ μ•ˆμ—λŠ” import ν•˜κ³  싢은 ν•¨κ΅¬μ˜ 이름을 μ“Έ 수 μžˆλ‹€.
  • import된 이름은 λ°˜λ“œμ‹œ export된 이름과 κ°™μ•„μ•Ό ν•œλ‹€. ('as'ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•΄μ„œ 이름을 λ°”κΏ€ 수 있음)

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, minus, divide } from './math';

plus(2,3);
minus(2,3);
divide(2,3);

main.js ('as'ν‚€μ›Œλ“œ μ‚¬μš©)


import { plus as add } from './math';

plus(2,3);
minus(2,3);
divide(2,3);

2. Default Export

  • 각 νŒŒμΌλ§ˆλ‹€ 단 ν•œκ°œμ˜ default export만 쑴재 ν•  수 있음
  • ν•œκ°œμ˜ νŒŒμΌμ—μ„œ λͺ¨λ“ κ±Έ exportν•˜κ³  import ν•  수 있음
  • μ›ν•˜λŠ” μ΄λ¦„μœΌλ‘œ import ν•  수 있음
  • νŒŒμΌμ—μ„œ λ”± ν•œκ°œλ§Œ export ν•˜κ³  μ‹Άμ„λ•Œ μ‚¬μš©ν•΄λ„ 됨

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,3);

3. Named Export 와 Default Export

  • νŒŒμΌμ—μ„œ 1개의 ν•¨μˆ˜λ§Œ exportλ₯Ό ν•˜κ³  싢을 λ•Œ : default export
  • named export - importλ₯Ό ν•œ μ€„μ˜ μ½”λ“œμ— μ„žμ„ 수 있음

db.js


const connnectToDB = () => { abc };
export const getUrl = () => { 111 };
export default connectToDB;

main.js


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

4. * (= everything)

  • λͺ¨λ“  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.plus(2,2);

5. Daynamic Import

  • μœ μ €κ°€ μ‚¬μš©ν•  λͺ¨λ“ˆλ§Œ import ν•  수 μžˆλ‹€.
  • async/await

λ³€κ²½μ „


function doMath() {
  import('./math)
  .then(math => math.plus(2,2));
}
btn.addEventListener('click', doMath);


λ³€κ²½ν›„


async function doMath() {
  const math = await import('./math');
  math.plus(2,2);
}
btn.addEventListener('click', doMath);
profile
κ°œλ°œλŒ•λ°œ

0개의 λŒ“κΈ€