Vuejs 구축

vuejs를 구축하기 위해 webpack, node가 필요하다.

webpack: 모듈번들러. 복잡하게 엵혀있는 JS 모듈들을 번들로 묶고 패킹함.

node: V8로 빌드된 이벤트 기반 자바스크립트 런타임.

vue cli

CLI를 통해 vue 템플릿을 받아 프로젝트를 구성할 수 있다. vue cli는 아래 명령으로 설치한다.

npm install vue-cli -g

vue cli 사용법

vue init webpack "프로젝트 이름"

vue_1

프로젝트 구조

프로젝트 설명은 아래와 같다.

vue_2

주요코드 분석

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>vuejs_practice</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

vuejs html 시작페이지이다. webpack을 통해 모듈화된 스크립트를 자동 호출하도록 설정되어 있다.

src/ 폴더에 있는 모든 js, vue, img 파일들은 모두 webpack에 의해 패킹되어 index.html이 호출한다.

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Vue 인스턴스를 생성하고, App.vue와 vue-router를 연동해준다. 또한 전역으로 처리할 일을 처리할 수 있다.

App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

가장 최상위인 컴포넌트이다. <router-view>를 통해 다른 vue 컴포넌트를 브라우저에 노출할 수 있다.

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})

vue-router를 통해 client의 path와 vue 컴포넌트를 매칭해주는 역할을 수행한다.

default로 path “/”을 입력하면 HelloWorld.vue가 매칭되도록 설정되어 있다.

compoments/HelloWorld.vue 코드는 길어서 생략했다. 디폴트로 제공되는 템플릿이 등록되어있다.

webpack-dev-server

해당 디렉토리 접근 후 아래 명령을 수행하면 웹팩 개발 서버가 동작한다.

npm run dev

웹팩 개발 서버는 프로젝트의 vue, js, img 등을 실시간으로 패킹한다.

중간에 vue를 수정하면 수정된 화면이 바로 반영된다.

Note: vue확장자 파일은 기본적으로 브라우저가 인식할 수 없다.

그렇기 때문에 webpack의 vue 로더가 vue확장자 파일을 브라우저가 인식할 수 있게 컨버팅 한다.

브라우저 접속

위 명령을 수행하면 cmd에 Your application is running here: http://localhost:8081 로그가 뜬것을 확인할 수 있다.

default는 8080이지만, 현재 spring boot application이 8080으로 실행중이기 때문에, 8081로 자동 증가한다.

그후 웹 브라우저에서 localhost:8081을 입력하면 아래 브라우저에 접속할 수 있다.

vue_3

빌드

npm run build

명령을 통해 빌드를 수행할 수 있다.

이후 dist/ 폴더가 생성되며 index.html과 static 폴더가 생성된다.

static 폴더안엔 css, js 폴더가 생성되어있음을 볼 수 있다.

생성된 index.html과 static 폴더를 웹서버 (nginx)에 배포하면 결과를 확인할 수 있다.

Comments