TIL #113 : [JavaScript] Modules

셀레스틴 허·2021년 3월 27일
0
post-thumbnail

Module?

하나의 파일에서 모든 일을 처리하는 시스템이 아닌 특정 업무를 맡은 작은 모듈들을 만든다.

  • 효율적으로 코드를 관리하고 디버그할 수 있으며
  • application의 여러 부분에서 재사용하기 쉽다
  • 다른 모듈으로부터 정보를 보호할 수 있다
  • global namespace, naming collision으로부터 보호할 수 있다

모듈을 쓸 수 있는 방법은 런타임 환경에 따라 두가지 방법이 있다:
1. Node.js 런타임 - module.exports, require()
2. 브라우저 런타임 - ES6 export, import

[Node.js] Module

한 파일에 모듈을 생성한 뒤 module.exports를 사용해 다른 파일에서도 사용하고 접근 가능하게 만들 수 있다

let Drink = {};
Drink.specialty = "Cool Lime Fizzio";
 
module.exports = Drink; 

-> Drink objects를 module로 export한다

require()

  • export한 module을 다른 파일에서 쓰고 싶을 때 다른 파일에서 require()로 import한다
  • require()는 javascript module을 load 한다
  • module을 로컬 변수에 담고 해당 변수를 통해 module의 property로 접근한다
  • drinkingBeverage() 함수는 Drink module을 쓴다
const Drink = require('./drink.js');
 
function drinkingBeverage() {
  console.log('I will have a ' + Drink.specialty);
}
 
drinkingBeverage();

module.exports

모듈 하나만 export할 수 있지만 다양한 data 그리고 함수를 객체 안에 담아서 보낼 수도 있다

module.exports = {
  kapoom: "I SAID KAPOOM!",
  blastOff: function() {
    return this.kapoom;
  } 
};
  • 해당 module은 객체로 export 된다
  • 객체에서 kapoom과 blastOff는 property다
만일 해당 모듈을 다른 파일로 불러와서 로그하고 싶다면...

const Kapoom = require('./originalkapoom.js');

console.log(Kapoom.blastOff());

[ES6] Module

named export

  • 재사용하고 싶은 함수는 이렇게 named export syntax를 통해서 처리할 수 있다
  • 해당 함수들은 export 선언 후 다른 파일들에서 사용할 수 있다
function getWater() {
  console.log('Keep me hydrated');
}

function getLunch() {
  console.log('Lunch Time!')

export {getWater, getLunch};

import

ES6 : import 구문으로 모듈을 가져온다

import { getWater, getLunch } from '/해당/파일로/가는/경로';
profile
Software Developer / 고통은 필연, 괴로움은 선택

0개의 댓글