node module 시스템

김정현·2024년 7월 2일

기타

목록 보기
25/26

모듈이란

기능 단위를 의미하며,
주로 외부 파일에서 함수(기능)을 불러올 때 사용된다.

CJS 방식과 ES모듈 방식으로 나뉜다.

CJS 방식 예시

//math 파일(함수가 저장된 파일)

function add(a, b) {
  return a + b;
}

function sub(a, b) {
  return a - b;
}

common js(CJS방식)
 module.exports = {
   add: add,
   sub: sub,
 };
//index 파일(함수를 불러오는 파일)

const { add, sub } = require("./math");

console.log(add(1, 2));
console.log(sub(1, 2));
console.log(mul(2, 3));

ES 모듈 방식

//math 파일(함수가 저장된 파일)
function add(a, b) {
  return a + b;
}

function sub(a, b) {
  return a - b;
}

//export default로 해당 파일을 대표하는 모듈의 기본값을 선언
export default function multiply(a, b) {
  return a * b;
}

export { add, sub };
//index 파일(함수를 불러오는 파일)

import mul, { add, sub } from "./math.js";

console.log(add(1, 2));
console.log(sub(1, 2));
console.log(mul(2, 3));
profile
개발 공부 블로그

0개의 댓글