본문 바로가기
💻CODING/javascript

[js] 자바스크립트 import , export 개념

by 코딩하는 갓디노 2021. 12. 30.

[js] 자바스크립트 import , export 개념

 

import, exprot의
가져오기, 내보내기 개념입니다.

 

자바스크립트의 import, export라는 키워드를 통해서 가져오기, 내보내기를 실행합니다. 

 

import 사용 예제 1

npm install로 node module 설치 후  
node_modules 폴더 안의 lodash 패키지를 _라는 이름으로 가지고 와서 
main.js에서 활용을 하겠다는 선언입니다.

 

main.js

import _ from 'lodash' //node_modules 폴더에서 가져오기

 

 

 import 사용 예제 2 - 상대 경로로 import

상대 경로를 통해서 외부에서 특정한 자바스크립트 파일(getToday.js)의 getToday 함수를 가져옵니다.

 

main.js

import getToday from './getToday'

 

export 사용 예제

export라는 키워드를 통해서 
getToday() 함수를 내부에서 외부로 내보내기를 합니다. 

getToday.js

export default function getToday() {
  let now = new Date();
  let todayYear = now.getFullYear();
  let todayMonth = (now.getMonth() + 1) > 9 ? (now.getMonth() + 1) : '0' + (now.getMonth() + 1);
  let todayDate = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();
  return todayYear + '-' + todayMonth + '-' + todayDate;
}

 

export의 두 가지 방법

default export

  • 이름을 따로 설정하지 않고 내보내기 - 이름이 없어도 됨
  • 하나의 데이터만 내보낼 수 있습니다.

export 할 때 따로 이름을 지정하지 않고 나갈 수 있으므로 getToday라는 이름이 없어도 실행합니다. 

export default function () {
	...
}

 

default export 된 자바스크립트 모듈을 import 할 때는 지정된 함수와 다른 이름을 사용하여도 무관합니다. 

import checkToday from './getToday' //getToday 에서 checkToday로

 


named export

  • 이름을 지정하고 내보내기 - default 키워드 사용 안 함
  • 복수의 데이터를 내보낼 수 있습니다.(개수의 제한이 없음)

export default가 아닌 export 만으로 내보내기 했을 경우 반드시 getToday와 같은 함수 이름이 필요합니다. 

export function getToday() {
  let now = new Date();
  let todayYear = now.getFullYear();
  let todayMonth = (now.getMonth() + 1) > 9 ? (now.getMonth() + 1) : '0' + (now.getMonth() + 1);
  let todayDate = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();
  return todayYear + '-' + todayMonth + '-' + todayDate;
}

 

  • import 할 때 무조건 같은 함수 이름 (getToday) 이름으로 import로 가져오기를 해야 합니다. 
  • 객체구조분해 문법과 같이 중가로 로 묶어서 사용해야 합니다. 
import { getToday } from './getToday'

 

함수 이름 바꾸기

as라는 키워드를 통해서 getToday를 today라 이름으로 바꿀 수 있습니다.

import { getToday as today } from './getToday'

 


named export 된 파일 내의 모든 함수를 한 번에 가져오기

*라는 키워드는 와일드카드라고 불리며 여러 내용을 한꺼번에 지정할 목적으로 사용하는 기호입니다.

export function getToday() {
  let now = new Date();
  let todayYear = now.getFullYear();
  let todayMonth = (now.getMonth() + 1) > 9 ? (now.getMonth() + 1) : '0' + (now.getMonth() + 1);
  let todayDate = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();
  return todayYear + '-' + todayMonth + '-' + todayDate;
}

export const today = () => {
  let now = new Date();
  let todayMonth = (now.getMonth() + 1) > 9 ? (now.getMonth() + 1) : '0' + (now.getMonth() + 1);
  let todayDate = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();
  return todayMonth + '-' + todayDate;
}

 

* 를 이용하여 today라는 이름으로 모든 getToday와 today 함수를 가지고 옵니다.

import { * as today } from './getToday'

 

 

 

 

반응형

댓글