Node.js 모듈 시스템

seungjun.dev·2025년 8월 11일

Node.js

목록 보기
8/13

하나의 파일에 모든 기능을 작성하는 대신, 관련 있는 함수나 변수, 클래스 등을 별도의 파일로 묶어서 관리

CommonJS (CJS) - 전통적인 방식

  • 모듈 내보내기: module.exports 또는 exports 객체에 내보내고 싶은 변수나 함수, 객체 할당
  • 모듈 가져오기: require() 함수를 사용
const hello = () => {
  console.log("Hello");
};

module.exports = {
  hello,
};
const helloModule = require("./hello.js");

helloModule.hello();

ES Modules (ESM) - 현대적인 표준 방식

  • 모듈 내보내기: export 키워드 사용
  • 모듈 가져오기: import 키워드 사용

Node.js에서 ESM을 사용하려면, package.json 파일에 "type": "module"을 추가하거나 파일 확장자를 .mjs로 사용해야 함

export const hello = () => {
  console.log("Hello");
};
import { hello } from "./helloModule.js";

// ...
profile
Frontend Engineer | Microsoft Student Ambassadors Alumni

0개의 댓글