서로 다른 파일에서 참조해서 사용하기 위해
math.js
const add = (x,y) => x+y;
const PI = 3.14159;
const square = x => x*x;
이 파일에 있는 add, PI, square들을 사용하고 싶을 때 module을 사용한다.
//math.js의 코드
const add = (x,y) => x+y;
const PI = 3.14159;
const square = x => x*x;
//mudule.exports를 하면 기본적으로 객체로 넘겨준다.
//module.exports.사용할 변수명(키값으로 들어감) = 사용할 값(벨류값으로 들어감) 사용해서 내보낸다.
module.exports.add = add;
module.exports.PI = PI;
module.exports.square = square;
//app3.js의 코드
//require를 통해서 math파일을 가지고 옴
const math = require('./math');
console.log(math);
노드에서 app3.js를 실행해보면
객체에 담겨서 설정해준 변수명이 키로 설정되고 사용할 값들이 밸류값으로 들어감
//app3.js
const math = require('./math');
console.log(math);
//받아온 math파일의 값들에 접근하는 방법
console.log(math.add(3,3));
console.log(math.PI);
console.log(math.square(4))
//구조분해 할당으로 접근하는 방법
//구조분해 할당으로
const {PI, add, square}= require('./math');
// console.log(math);
console.log(add(3,3));
console.log(PI);
console.log(square(4))
//객체 자체를 넘기는 방법
const add = (x,y) => x+y;
const PI = 3.14159;
const square = x => x*x;
//math.js
//넘길 것들을 오브젝트에 담아서 넘겨줌
//넘어간 데이터 값들은 key값으로 접근함
const math ={
add:add,
PI:PI,
suee:square,
}
module.exports=math;
//app3.js
const math= require('./math');
console.log(math);
console.log(math.add(3,3));
console.log(math.PI);
console.log(math.suee(4))
//오브젝트로 넘긴 것도 구조분해 할당으로
//app3.js
//구조분해 할당으로
const {PI, add, suee}= require('./math');
// console.log(math);
console.log(add(3,3));
console.log(PI);
console.log(suee(4))