[VanillaJS] SPA기본구조 잡기

Chanho Kim·2021년 8월 30일
7

[vanillajs] 영화 앱

목록 보기
2/4

1. Single Page Application이란?

Single Page Application(SPA)은 서버로부터 완전한 새로운 페이지를 불러오지 않고 현재의 페이지를 동적으로 다시 작성함으로써 사용자와 소통하는 웹 애플리케이션이나 웹사이트를 말한다. 이러한 접근은 연속되는 페이지들 간의 사용자 경험의 간섭을 막아주고 애플리케이션이 더 데스크톱 애플리케이션처럼 동작하도록 만들어준다. SPA에서 HTML, 자바스크립트, CSS 등 필요한 모든 코드는 하나의 페이지로 불러오거나,ajax 등으로 적절한 자원들을 동적으로 불러들여서 필요하면 문서에 추가하는데, 보통 사용자의 동작에 응답하게 되는 방식이다.

출처: https://www.excellentwebworld.com/what-is-a-single-page-application/

2. 구현

2-1. 기본 구조

다음과 같은 폴더 구조로 기본 작업을 시작합니다.

├── index.html
└── src
    ├── App.js
    ├── main.js
    └── components
        └── Hello.js

2-2. index.html

head에 spa를 만들기 위한 javascript를 연결해줍니다. 이때 type을 module로 꼭 줘야합니다.

<script type="module" src="./src/main.js"></script>

body에는 어플리케이션이 직접 랜더링 될 div를 app이라는 class를 줘서 만들어 줍니다.

<div class="app"></div>

index.html 전체 코드

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>JS STUDY</title>
    <link rel="stylesheet" href="./src/css/style.css" />
    <script type="module" src="./src/main.js"></script>
  </head>
  <body>
    <div class="app"></div>
  </body>
</html>

2-3. main.js

컴포넌트를 직접 랜더링 할 index.html에 있는 div를 querySelector로 선택해 추후에 작성할 App.js에 넘겨줍니다.

import App from './App.js';

const app = new App(document.querySelector('.app'));

2-4. app.js

app.js에서는 main.js에서 넘겨준 div를 Hello컴포넌트로 전달해 랜더링 준비를 합니다.

import Hello from './components/Hello.js';

export default class App {
  constructor($target) {
    const hello = new Hello({
      $target
    });
  }
}

2-5. Hello.js

constructor에서 section element를 만들어 준 뒤 index.html에서 전달 한 div에 append해줍니다.
그 후에 render 함수에서 h1 element를 만들어 준 뒤 section element에 append해줍니다.
마지막으로 constructor에서 render함수를 호출해 줍니다.

export default class Hello {
  constructor({ $target }) {
    this.section = document.createElement("section");
    $target.appendChild(this.section);
    this.render();
  }

  render() {
    this.section.innerHTML = "";
    const text = document.createElement("h1");
    text.innerText = "hello world!";
    this.section.appendChild(text);
  }
}

2-6. 실행

간단하게 실행해 보기 위해 http-server를 사용해 보겠습니다.
root directory에 가서 다음 명령어를 실행해 줍니다.

npx http-server ./


다음과 같이 서버가 8080 포트에 실행됩니다.
http://localhost:8080 에가서 확인해 보면
SPA로 작성한 hello world!를 만날 수 있습니다.

참고 사이트

https://ko.wikipedia.org/wiki/%EC%8B%B1%EA%B8%80_%ED%8E%98%EC%9D%B4%EC%A7%80_%EC%95%A0%ED%94%8C%EB%A6%AC%EC%BC%80%EC%9D%B4%EC%85%98
https://github.com/woohyeonjo/ilovecat-javascript

profile
호기심쟁이 FE개발자 김찬호입니다!

2개의 댓글

comment-user-thumbnail
2021년 8월 30일

좋은 정보 감사합니다 :)

1개의 답글