[JavaScript] 31. Node.js의 모듈 시스템

서회정's avatar
Feb 05, 2026
[JavaScript] 31. Node.js의 모듈 시스템

1. 모듈 시스템이란

💡
기능에 따라 파일을 분리해서 관리하는 시스템
버그 수정에도 용이하며 재사용성을 높일 수 있고 협업에 유리하다.
전역변수 관리도 편리해 충돌을 사전에 막을 수 있다.
notion image
notion image
notion image
 

2. CJS와 ESM의 차이점

구분
CJS (CommonJS)
ES Module (ESM)
기본 문법
require, module.exports
import, export
표준 여부
Node.js 전용
JavaScript 공식 표준
로딩 방식
동기 로딩
비동기 로딩
구조
동적 (런타임 결정)
정적 (컴파일 타임 결정)
조건부 로딩
가능
불가능
트리 쉐이킹
브라우저 사용
사용 환경
레거시 Node 프로젝트
프론트엔드, 최신 Node
현재 권장도
❌ (유지보수용)
✅ (기본 선택)

3. CJS 모듈 시스템

💡
Common JS 모듈 시스템
 

1. math 모듈 만들기

index.js와 동일한 경로에 해당 모듈을 만들고 내보내보자
 
math.js
// math 모듈 function add(a, b) { return a + b; } function sub(a, b) { return a - b; } // 두 개의 함수 내보내기 module.exports = { add, sub, };
 
모듈이라는 내장객체에 exports라는 프로퍼티의 값으로 객체를 저장한다.
CommonJS 모듈 시스템에 의해 두 개의 값이 Math 모듈로부터 내보내지게 된다.
 

2. math 모듈 받기

index.js에서 require 내장함수를 통해 인수로 전달하며 객체 형태로 그대로 반환해주자
 
index.js
const moduleData = require("./math"); console.log(moduleData);
 
require 내장함수로 받은 math모듈의 함수들을 객체 형태 그대로 moduleData 변수에 담아 다음과 같이 출력할 수 있다.
 
notion image
 

3. 함수 호출해보기

const moduleData = require("./math"); console.log(moduleData.add(1, 2)); console.log(moduleData.sub(1, 2));
notion image
 
객체 구조분해할당으로 다음과 같이 보다 간결하게 코드를 작성할 수도 있다.
const { add, sub } = require("./math"); console.log(add(1, 2)); console.log(sub(1, 2));
 

4. ESM 모듈 시스템

💡
ES Module
대중적으로 사용!
 

1. ES 모듈 시스템 사용 명시

 
package.jason에 있는 typecommonjs 대신 module이라 작성한다.
 
notion image
 
이때 먼저 작성해두었던 코드를 실행해보면 터미널에 다음과 같은 오류 메세지를 확인할 수 있는데, 설정된 모듈 시스템, 즉 ES module로는 require을 사용할 수 없다 라는 의미로 생각하면 된다.
 
notion image
 

2. math 모듈 내보내기

💡
export 키워드 뒤에 객체를 리터럴로 만들어서 내보내고 싶은 값들을 담아준다
 
math.js
// math 모듈 function add(a, b) { return a + b; } function sub(a, b) { return a - b; } // 두 개의 함수 내보내기 export { add, sub };
 

3. math 모듈 받기

💡
import 키워드 뒤에 받아올 값들을 적어주고 어디로부터 값을 가져올 지 from 뒤에 경로를 작성해준다. 이때 경로의 확장자까지 꼭 적어야한다!
 
index.js
import { add, sub } from "./math.js"; console.log(add(1, 2)); console.log(sub(1, 2));
notion image
 

5. ES 모듈 시스템에서 값을 내보내고 가져오는 다양한 방법

 

1. 내보내고 싶은 함수 앞에 export 작성

// math 모듈 export function add(a, b) { return a + b; } export function sub(a, b) { return a - b; }
 

2. 해당하는 경로를 대표하는 기본값인 default로 내보내기

// math 모듈 export function add(a, b) { return a + b; } export function sub(a, b) { return a - b; } export default function multiply(a, b) { return a * b; }
받을 때 중괄호 없이 받을 수 있다.
import multiply from "./math.js"; import { add, sub } from "./math.js"; console.log(add(1, 2)); console.log(sub(1, 2));
default는 하나의 경로에 단 하나만 존재하기 때문에 이름을 바꿔서 가져와도 찾을 수 있다.
import mul from "./math.js"; import { add, sub } from "./math.js"; console.log(add(1, 2)); console.log(sub(1, 2)); console.log(mul(1, 2));
같은 경로에서 가져오는 여러 값들은 함께 import 할 수 있다.
import mul, { add, sub } from "./math.js"; console.log(add(1, 2)); console.log(sub(1, 2)); console.log(mul(1, 2));
Share article

clubnerdy