StoryCode

import, export

JavaScript, ECMAScript
반응형

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

 

아래 4가지 import 문장의 차이 이해

import { Module } from './module';
import   Module   from './module';
import * as myModule from './module';
const Module = await import('./module');

 

math.js # export main.js # import 추가설명
1) 개별 export 방식
  export const plus = (a, b) => a+b;
  export const minus = (a, b) => a-b;
  export const divide = (a, b) => a/b;
1) 개별 import 방식 (=named import)
import {plus} from "./math";
plus(2, 2);
혹은
import {plus as add} from "./math";
add (2, 2);
- {} 를 꼭 써야 하는 방식을 named import 라 함. 
- plus 란 이름 동일해야 함.
- 바꾸려면 as 로 변경 가능
2) 통합 export 방식
  export const plus = (a, b) => a+b;
  export const minus = (a, b) => a-b;
  export const divide = (a, b) => a/b;
  export default {plus, minus, divide};
2) 통합 import 방식
import myMath from "./math";

myMath.plus(2, 2);
- "export default"를 import 시 {} 를 안 쓴다.
- {} 안쓴 import "export default"  통째로 import 하는 .
3) 혼합 export 방식
const connectToDB = () => {/*code*/}
export const getUrl = () => {/*code*/}
3) 혼합 import 방식
import connect, {getUrl} from "./db";
- 개별 import 와 통합 import 를 혼용할 때.
4) 개별 일괄 export 방식
  const plus = (a, b) => a+b;
  const minus = (a, b) => a-b;
  const divide = (a, b) => a/b;
4) 개별 일괄 import 방식
import * as myMath from "./math";
myMath.plus(2, 2);
- export 가 없음.
  5) Dynamic import 방식 1
function doMath() {
    import("./math")
    .then(math => math.plus(2,2));
}

btn.addEventListener("click", doMath);

 
  5) Dynamic import 방식 2
async function doMath() {
    const math= await import("./math");
    math.plus(2,2);
}

btn.addEventListener("click", doMath);
 

 

반응형