React/한입크기로 잘라먹는 리액트
[Node.js] 모듈 시스템 이해하기
냠냠쿠
2025. 1. 10. 13:49
728x90
1. CommonJS 방식
1. 다른 js파일에 있는 함수를 가져오기
math.js에 있는 함수를 index.js에서 쓸 때
math.js
//math 모듈
function add(a,b){
return a+b;
}
function sub(a,b){
return a-b;
}
// Common.js 모듈 시스템 이용
// 모듈 내장 객체에 exports라는 프로퍼티 값으로 객체 저장
//모듈 내보내기
module.exports= {
//add : add,
//sub : sub,
//변수의 키/값이 같다면 하나만 적어도 됨
add,
sub,
};
idnex.js
//모듈을 불러오기
require("./math");
//불러온 모듈을 변수에 담아보기
const moduleData = require("./math");
console.log(moduleData);
console.log("hello Node.js");
그리고 터미널에서 npm run start를 입력하면 math 모듈로부터 불러온 함수가 잘 넘어온 것을 볼 수 있다.
2. 사용하기
//모듈 사용하기
console.log(moduleData.add(1,2));
console.log(moduleData.sub(5,1));
객체의 구조분해 할당으로도 가능
const {add, sub} = require("./math");
//모듈 사용하기
console.log(add(1,2));
console.log(sub(5,1));
2. ES 모듈시스템 방식
1. 패키지 설정
{
"name": "section03",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node index.js"
},
"author": "",
"license": "ISC",
"description": "",
"type" : "module" //type에 module 추가
}
type:module은 섹션3 패키지는 ES 모듈 시스템을 사용하겠다라는 뜻임
2. 함수를 내보내고 가져오기
math.js
//내보내고 싶은 함수 담기
export {add, sub};
혹은 함수앞에 export를 붙여주면된다.
//math 모듈
export function add(a,b){
return a+b;
}
export function sub(a,b){
return a-b;
}
index.js
//값 가져오기
import {add, sub} from "./math.js";
console.log(add(1,2));
console.log(sub(1, 12));
3.default 값 내보내는 경우
export default function multiply(a, b){
return a*b;
}
default 를 붙이게 되면 math 모듈을 대표하는 하나의 가본값이 된다.
그래서 다른 모듈에서 임포트로 불러올 때 중괄호 안에 새로운 import문을 만들어줘야한다.
//값 가져오기
import multiply from "./math.js"; //새로운 import 해줘야함
import {add, sub} from "./math.js";
4. 동일한 경로로부터 값을 가져오는 경우
import 시 합치기도 가능
//값 가져오기
import multiply, {add, sub} from "./math.js";
728x90