Backend/Node.js
Module
AIHYEONJI
2025. 4. 27. 11:34
모듈
: JS 모듈은 코드의 재사용성과 유지보수성을 높이기 위해 기능을 개별 파일로 분리하여 사용할 수 있도록 해주는 구조이다.
export 키워드를 사용하여 모듈에서 변수, 함수, 클래스 등을 외부로 내보내고. import 키워드를 사용하여 다른 파일에서 이들을 불어와 사용할 수 있다.
이를 통해, 전역 변수 오염을 방지하고, 각 기능을 독립적으로 관리할 수 있어 복잡한 애플리케이션 개발에 적합한 구조를 제공한다.
1. CommonJs 방식의 모듈
📁 counter.js (모듈 파일)
let count = 0;
function increase() {
count++;
}
function getCount() {
return count;
}
// 모듈화 -> getCount 함수를 새로 만들어 주소만 전송
// 모듈화로 인해 외부에서 직접 접근 가능함
module.exports.getCount = getCount;
module.exports.increase = increase;
- count 변수는 외부에서는 직접 접근할 수 없습니다. (private한 변수처럼 동작)
- 외부에서는 increase()와 getCount() 함수만 사용할 수 있습니다.
- 모듈은 해당 파일의 내용을 은닉하고 필요한 것만 노출 → 캡슐화
📁 main.js (모듈 사용하는 파일)
const counter = require("./counter.js");
counter.increase();
counter.increase();
counter.increase();
console.log(counter.getCount());
2. ES6 방식의 모듈
📁 counter.mjs (모듈 파일)
let count = 0;
export function increase() {
count++;
}
export function getCount() {
return count;
}
📁 main.mjs (모듈 사용하는 파일)
let count = 0;
function increase() {
count++;
}
function getCount() {
return count;
}
// 모듈화 -> getCount 함수를 새로 만들어 주소만 전송
// 모듈화로 인해 외부에서 직접 접근 가능함
module.exports.getCount = getCount;
module.exports.increase = increase;
3. CommonJS vs ES6 모듈 차이