하나의 파일에서 모든 일을 처리하는 시스템이 아닌 특정 업무를 맡은 작은 모듈들을 만든다.
모듈을 쓸 수 있는 방법은 런타임 환경에 따라 두가지 방법이 있다:
1. Node.js 런타임 - module.exports
, require()
2. 브라우저 런타임 - ES6 export, import
한 파일에 모듈을 생성한 뒤 module.exports
를 사용해 다른 파일에서도 사용하고 접근 가능하게 만들 수 있다
let Drink = {};
Drink.specialty = "Cool Lime Fizzio";
module.exports = Drink;
-> Drink objects를 module로 export한다
require()
로 import한다require()
는 javascript module을 load 한다Drink
module을 쓴다const Drink = require('./drink.js');
function drinkingBeverage() {
console.log('I will have a ' + Drink.specialty);
}
drinkingBeverage();
모듈 하나만 export할 수 있지만 다양한 data 그리고 함수를 객체
안에 담아서 보낼 수도 있다
module.exports = {
kapoom: "I SAID KAPOOM!",
blastOff: function() {
return this.kapoom;
}
};
만일 해당 모듈을 다른 파일로 불러와서 로그하고 싶다면...
const Kapoom = require('./originalkapoom.js');
console.log(Kapoom.blastOff());
function getWater() {
console.log('Keep me hydrated');
}
function getLunch() {
console.log('Lunch Time!')
export {getWater, getLunch};
ES6 : import 구문으로 모듈을 가져온다
import { getWater, getLunch } from '/해당/파일로/가는/경로';