[javascript] Parcel에서 모달 창을 구현하는 방법은?

먼저, Parcel 프로젝트를 생성하고 필요한 종속성을 설치해야 합니다. 다음 명령어를 사용하여 프로젝트를 초기화합니다.

npm init -y
npm install parcel-bundler

Parcel을 사용하기 위해 index.html 파일을 생성하고, 아래와 같은 기본 구조를 추가합니다.

<!DOCTYPE html>
<html>
<head>
  <title>Modal Example</title>
</head>
<body>
  <button id="showModalButton">Show Modal</button>
  <div id="modal" style="display: none;">
    <div id="modalContent">
      <h2>Modal Content</h2>
      <p>This is an example modal.</p>
      <button id="closeModalButton">Close</button>
    </div>
  </div>
  <script src="./index.js"></script>
</body>
</html>

버튼을 클릭하면 모달 창이 나타나도록 하기 위해 JavaScript 파일(index.js)을 생성합니다. 이 파일에는 Parcel에 의해 번들링될 스크립트 코드를 작성합니다.

function showModal() {
  document.getElementById("modal").style.display = "block";
}

function closeModal() {
  document.getElementById("modal").style.display = "none";
}

document.getElementById("showModalButton").addEventListener("click", showModal);
document.getElementById("closeModalButton").addEventListener("click", closeModal);

index.js 파일은 showModal()과 closeModal() 함수를 정의하고, 버튼 클릭 이벤트에 이 함수들을 연결합니다. 모달이 나타나거나 사라지도록 display 속성을 조작합니다.

모든 파일이 설정되었으면, 터미널에서 다음 명령어를 실행하여 Parcel을 시작합니다.

npx parcel index.html

Parcel은 프로젝트를 번들링하고 로컬 개발 서버를 구동합니다. 서버가 생성되면 브라우저에서 http://localhost:1234로 이동하여 모달 데모를 확인할 수 있습니다.

이제 Parcel을 통해 모달 창을 구현하는 방법을 알게 되었습니다. Parcel은 번들링 및 개발 서버 기능을 제공하여 웹 개발을 간편하게 할 수 있습니다.

참고 자료