JS - Require vs Import

Yuni·2023년 4월 2일
0

JS

목록 보기
10/17
post-thumbnail

자바스크립트에서 require와 import는 모듈 시스템에서 사용되는 키워드로 두 키워드 모두 외부 파일이나 라이브러리를 불러올 때 사용합니다. 두 키워드 모두 다른 파일의 코드를 불러온다는 점은 같지만, 다른 문법 구조를 지니고 있습니다.



require/exports(Common JS)

require는 CommonJS 키워드로(Node js) 변수를 할당하듯 모듈을 불러오는 것이 특징입니다.

기본 문법

//exports (module.js)
const name = 'yuni';
module.exports = name;
//require (index.js)
const name = require('./module.js');

모듈 전체 내보내고 가져오기

여러개의 객체를 내보낼 때 → exports.변수

// 모듈 전체를 export, 파일내 한번만 사용가능(module.js)
const obj = {
   num: 10,
   sum: function (a, b) {
      console.log(a + b);
   },
   extract: function (a, b) {
      console.log(a - b);
   },
};
module.exports = obj;
// require (index.js)
const obj = require('./module.js');

obj.num; // 10
obj.sum(10, 20); // 30
obj.extract(20, 10); // 10

모듈 개별 내보내고 가져오기

딱 하나의 객체를 내보낼 때 → module.exports = 객체

// exports
exports.name = 'yuni'; // 변수

exports.greeting = function() { // 함수
    console.log('hello');
}

exports.Person = class Person { // 클래스
    constructor(name){
        this.name = name;
    }
}
// require
const { name, greeting, Person } = require('./exportFile.js');

console.log(name); // yuni
greeting(); // hello
const person = new Person('mimi');



import / export (ES6)

ES6에서 새롭게 도입된 키워드입니다. import는 모듈의 이름이나 경로를 정적으로 분석하기 때문에 실행 시간에 모듈을 가져올 수 없습니다. 따라서, import는 반드시 최상단에서 선언되어야 합니다.

기본 문법

// export (module.js)
const name = 'yuni';
export default name;
// import (index.js)
import name from './module.js'

모듈 전체 내보내고 가져오기

// 모듈 전체를 export, 파일내 한번만 사용가능(module.js)
const obj = {
   num: 10,
   sum: function (a, b) {
      console.log(a + b);
   },
   extract: function (a, b) {
      console.log(a - b);
   },
};

export default obj; // 전체 자체를 export 할 경우 중괄호 없이 기재
import obj from './module.js';

obj.num; // 10
obj.sum(10, 20); // 30
obj.extract(20, 10); // 10

모듈 개별 내보내고 가져오기

1) 키워드 앞에서 export 하기

export const name = 'yuni'; // 변수 export

export function greeting() { // 함수 export
    console.log('hello');
}

export class Person { // 클래스 export
    constructor(name){
        this.name = name;
    }
}

2) 마지막에 내보내는 모듈을 객체로 모아 export 하기

const name = 'yuni';

function greeting() {
    console.log('hello');
}

class Person {
    constructor(name){
        this.name = name;
    }
}

export {name, greeting, Person}; // 변수, 함수, 클래스를 하나의 객체로 구성하여 export
//import
import { name, greeting, Person } from './exportFile.js';


마무리

많은 프로젝트에서 ES6 모듈 시스템을 점점 널리 사용하는 추세이지만, script태그를 사용하는 브라우저 환경이나 CommonJS를 기본 모듈 시스템으로 채택하고 있는 NodeJS에서는 require를 사용해야 합니다. (Babel과 같은 ES6 코드를 변환해주는 도구를 사용하거나요.)




참고
https://hsp0418.tistory.com/147
https://velog.io/@hye_rin/React-require%EC%99%80-import%EC%9D%98-%EC%B0%A8%EC%9D%B4

profile
Look at art, make art, show art and be art. So does as code.

0개의 댓글