관리 메뉴

개발캡슐

[JS, Node.js] require, import 키워드 문법 본문

용어 및 개념 정리/javascript

[JS, Node.js] require, import 키워드 문법

DevGreeny 2023. 4. 3. 11:32

require, import

require, import


require, import 두 개의 키워드는 모두 하나의 파일에서 다른 파일의 코드를 불러온다는
동일한 목적을 가지고 있어.
기본적으로 MomentJS라는 라이브러리를 불러오는 동일한 작업을 수행하지.
동일한 목적이지만 다른 문법을 가지고 있어.

require

- NodeJS에서 사용되고 있는 CommonJS키워드야.
- CommonJS방식을 따른 첫번째 코드는 require키워드를 사용해서 다른 변수를 할당하듯이 모듈을 불러와.
- 주의사항으로, CommonJS방식으로 모듈을 내보낼 때는 특정 변수나 그 변수의 속성으로 내보낼 객체를 세팅해줘야 해.
(ES6처럼 명시적으로 선언하는 게 아니야.)

1. 여러 개의 객체를 내보낼 경우, export 변수의 속성으로 할당해.
2. 딱 하나의 객체를 내보낼 경우, module.exports 변수 자체레 할당해.
단, 객체를 묶어서 여러개 값을 export할 수 있어.

 

< require 사용법 >

- Babel과 같은 ES6 코드를 변환(transpile)해주는 도구를 사용할 수 없는 경우엔 require 키워드를 사용해야 해.

- require는 이런 상황일 때 사용할 수 있어.
1. 노드 복수 객체를 내보내고 불러올 때
2. 노드 단일 객체를 내보내고 불러올 때.
3. require 함수의 인수에 파일뿐만 아니라 디렉토리를 지정할 때. (require 디렉토리)
4. 변수에 대입하지 않고 즉시 실행할 때 (즉시 실행하기)

- 모듈 불러오기

const moment = require("moment");
/* test-currency-functions.js */

const currency = require("./currency-functions");

console.log("50 Canadian dollars equals this amount of US dollars:");
console.log(currency.canadianToUs(50));

console.log("30 US dollars equals this amount of Canadian dollars:");
console.log(currency.usToCanadian(30));

 

- 모듈 내보내기

/* currency-functions.js */

const exchangeRate = 0.91;

function roundTwoDecimals(amount) {
  return Math.round(amount * 100) / 100;
}

const canadianToUs = function (canadian) {
  return roundTwoDecimals(canadian * exchangeRate);
};

function usToCanadian(us) {
  return roundTwoDecimals(us / exchangeRate);
}

exports.canadianToUs = canadianToUs; // 내보내기 1
exports.usToCanadian = usToCanadian; // 내보내기 2

 


import

- ES6(ES2015)에서 새롭게 도입된 키워드야.
- ES6 방식을 따라 import 키워드를 사용해서 좀 더 명시적으로 모듈을 불러와.
- 외부 스크립트 또는 외부 모듈의 export된 함수, 객체를 가져오는데 사용돼.

- 모듈에는 특수한 지시자 export와 import를 적용하면 다른 모듈을 불러와 불러온

모듈에 있는 함수를 호출하는 것과 같은 공유가 가능해.

모듈은 단지 파일 하나에 불과해. 스크립트 하나는 모듈 하나야.

출처 :&nbsp;https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-%EB%AA%A8%EB%93%88-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-import-export-%EC%A0%95%EB%A6%AC?category=889099#%EB%AA%A8%EB%93%88_import



< import 사용법 >

- import는 이런 6가지 상황일 때 사용할 수 있어.

1. 모듈 전체 가져올 때
2. 하나의 모듈을 가져올 때
3. 여러개의 모듈을 가져올 때
4. 다른 이름으로 모듈 가져올 때
5. 바인딩 없이 모듈만 실행할 때
6. default export 값을 가져올 때

모듈 전체 가져오기

// 모듈 전체 가져오기
import * as myModule from "my-module.js";
// myModule.sayHello()

 

하나의 멤버 가져오기

import {myMember} from "my-module.js";

 

다른 이름으로 멤버 가져오기

- 멤버를 가져올 때 다른 이름으로 멤버를 지정할 수 있어.
- export된 멤버 이름이 길거나, 복잡할 때, 임의의 이름으로 멤버를 지정할 수 있어.

import {reallyReallyLongModuleMemberName as shortName} from "my-module.js";
import {reallyReallyLongModuleMemberName as shortName, anotherLongModuleName as short} from "my-module.js";

 

< 사용법 예시 >

//named
import * as name from "module-name";
import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name"; // member 이름이 길 경우 as 별명 가능.
import { member1 as member2 } from "module-name";
import { member1, member2 as alias2, [...]  } from "module-name";


// default
import defaultMember, { member [, [...]] } from "module-name";
import defaultMember, * as alias from "module-name";
import defaultMember from "module-name";
import "module-name";

/*
   name : 가져온 값을 받을 객체 이름.
   member, memberN : export 된 모듈에서 멤버의 이름
   defaultMember : export 된 모듈의 default 이름
   alias, aliasN : export된 멤버의 이름을 지정한 이름
   module-name : 가져올 모듈 이름 (파일명)
*/

 

require 와 import의 차이점


- 하나의 프로그램에서 두 키워드를 동시에 사용할 수 없어.
- require()는 CommonJS를 사용하는 node.js문이지만 import()는 ES6에서만 사용해.
- require()는 파일(어휘가 아님)에 들어갈 곳에 남아 있고 import()는 항상 맨 위로 이동해.
- require()는 프로그램의 어느 지점에서나 호출할 수 있고 import()는 조건부로 호출할 수 없고 파일의 시작 부분에서만 실행할 수 있어.
(import 전용 비동기 문법으로 파일 중간에 모듈 불러오기를 할 수 있어.)
- 일반적으로 import ()는 사용자가 필요한 모듈 부분만 선택하고 로드할 수 있기 때문에 더 선호되고,
require()보다 성능이 우수하고 메모리를 절약해.
- ES 모듈은 require()와 달리 import() 함수를 통해 동적으로 로드할 수 있어.

 

CF)

- Node.js가 최신 자바스크립트 문법들은 지원하지만 모듈 시스템으로
CommonJS를 채택했기 때문에 ES 모듈 시스템은 사용할 수 없어.

 


 

 

 

-참고자료-