본문 바로가기

🥸 웹앱개발 이모저모/Java Script

[JS] 모듈 만들기, 내보내기, 가져오기

모듈

: 작은 기능 단위로 쪼개서 각 기능별로 만들어 놓은 함수

모듈은 파일 형태로 저장하고 필요할 때 마다 가져와서 사용함

const user = "무말콩";

const hello = (name) => {
  console.log(`${name}님 안녕하세요.`);
};

hello(user);

이 코드를 사용자 이름을 가져와서 인사말을 표시할 수 있도록

user.js와 hello.js 이렇게 2개의 모듈로 나누어 보자.

모듈 내보내기

user.js

const user ="무말콩";

module.exports = user; //user라는 변수로 내보낸다는 의미

hello.js

방법 1

const hello = (name) => {
  console.log(`${name} 님, 안녕하세요?`);
};

module.exports = hello; //hello 함수로 내보내기

방법 2

exports.hello = (name) => {
  console.log(`${name} 님, 안녕하세요?`);
};

함수 앞에 exports를 붙여서 함수를 직접 내보낼 수도 있다.

모듈 가져오기

위에서 만든 모듈을 어떻게 가져와서 사용하는 지 알아보자.

CommonJS 모듈 시스템에서 모듈을 가져올 때는 require 함수를 사용한다. (이렇게 모듈을 가져오는 행동을 import라고 한다.)

app.js

const user = require("./user.js"); //user.js에서 user 가져오기
const hello = require("./hello.js"); // hello.js에서 hello 가져오기

hello(user); // 가져온 hello와 user 사용하기

require(”경로”) 이때 경로는 상대 경로로 자신의 파일 경로에 맞게 작성해주면 된다.

또한 ./user.js 이지만 확장자인 .js는 생략할 수 있음

 

const 변수명 = require("모듈명");