logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [Vue] Vue3 + Vite + TS 프로젝트 시작하기(feat. router, vuex, scss)

    이미지 보기

    [Vue] Vue3 + Vite + TS 프로젝트 시작하기(feat. router, vuex, scss)

    • 22.07.04 작성

    • 읽는 데 6

    TOC

    Vue3 + Vite + TS 프로젝트 시작하기

    • Vite: First Vite Project
    • vue create 명령어는 webpack 번들러를 사용
    • vite 번들러를 사용하기 위해서는 vite app을 생성해야 함
    $ npm init vite@latest <app-name> -- --template vue-ts
    
    $ cd <app-name>
    
    $ npm run dev
    

    ./src를 @로 등록

    • 기존 vue 프로젝트는 @ 표시를 자동으로 src의 의미로 사용
    • vite 앱은 별도의 설정이 필요
    • 📃vite.config.ts 에서 다음과 같이 설정
    // vite.config.ts
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import path from 'path'
    
    export default defineConfig({
      plugins: [vue()],
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src'),
        }
      }
    })
    

    path에 오류가 생기는데요?

    $ npm install --save @types/node
    

    또 무슨 오류가 생기는데요?

    image
    • allowSyntheticDefaultImports를 사용한다고 처리해주어야 한다.
    // tsconfig.node.json
    "compilerOptions": {
      ...
      "allowSyntheticDefaultImports": true,
    },
    
    • 참고 블로그
    • 위의 블로그는 tsconfig.json에 추가하라고 하였으나, 나의 경우 tsconfig.node.json에 추가하니 오류가 해결되었다.

    Vue router 적용


    vue router4 설치

    • Vue3에서는 vue-router@4(버전 4)가 필요
    $ npm install vue-router@4
    

    router 파일 생성

    • 📂src 내에 📃router.ts 생성
    // router.ts
    import { createRouter, createWebHistory } from 'vue-router';
    
    const routes: any[] = []
    const router = createRouter({
      history: createWebHistory(),
      routes,
    })
    
    export default router
    

    Vue 앱이 router를 사용하게 하기

    • 📃main.ts에 router 사용 코드 추가
    // main.ts
    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router' 🔆
    
    createApp(App)
      .use(router) 🔆
      .mount('#app')
    

    routes 채우기

    • 📂src 내에 📂views 생성

    • 📂views 내에 path에 따라 이동할 view vue 파일 생성

    • 예시로는 📃Home.vue, 📃Login.vue 생성

    • 📂src 내에 📃router.ts 생성

    import { createRouter, createWebHistory } from 'vue-router';
    
    const routes: any[] = [
      // 홈 화면
      {
        path: '/',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
      },
    
      // 로그인 화면
      {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
      },
    
      ...
    ]
    
    const router = createRouter({
      history: createWebHistory(),
      routes,
    })
    
    export default router
    
    • router(Array) 내부에 route(Object) 정보 추가
    • 각 route는 path, name, component로 구성
    • component는 동적 import

    App.vue에 router-view 추가

    <!-- App.vue -->
    <script></script>
    
    <template>
      <router-view /> 🔆
    </template>
    
    <style></style>
    
    • template에 router-view 추가
    • path에 따라 router에 지정된 path가 router-view 위치에 component vue file이 위치

    vuex 적용


    vuex4 설치

    $ npm install vuex@next --save
    

    store과 index.js 생성

    • 📂src 내에 📂store 생성
    • 📂store 내에 📃index.ts 생성
    import { createStore } from 'vuex';
    import reservation from './modules/reservation';
    
    // store 변수를 만들어서 export 한다는 점에 주의! 
    export const store = createStore ({
      modules: { reservation },
    });
    
    • 모듈을 import해서 createStore로 생성한 store 내에 추가
    • 이 store를 export하여 사용

    모듈 reservation 생성

    • store에 넣을 module을 만들어보자.
    // @/store/modules/reservation/index.ts
    import MUTATIONS from './mutation';
    
    const state = {
      reservations: [],
    };
    
    const getters = {
      reservations: (_state: any) => {
        return _state.reservations;
      }
    };
    
    const actions = {
    };
    
    const mutations = {
      [MUTATIONS.SET_RESERVATIONS]: (_state:any, list:any) => {
          _state.reservations = list;
      }
    };
    
    export default {
      namespaced: true,
      state,
      getters,
      actions,
      mutations,
    };
    
    • 오류를 피하기 위해 임시로 any type을 정의해주었다.
    • MUTATION를 import해올 📃mutation.ts는 다음과 같다.

    // @/modules/reservation/mutations.ts
    const MUTATIONS = {
      SET_RESERVATIONS: 'setReservations',
    };
    
    export default MUTATIONS;
    

    main.ts에 store 추가

    • store를 📃main.ts에 추가해야 사용 가능
    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router'
    import { store } from './store' 🔆
    
    createApp(App)
      .use(store) 🔆
      .use(router)
      .mount('#app')
    

    vue instance에서 사용

    <script>
    import { createNamespacedHelpers } from 'vuex';
    import MUTATIONS from '@/frontend/src/store/modules/reservation/mutation';
    
    const { mapGetters, mapMutations } = createNamespacedHelpers('reservation');
    
    export default {
      name: 'HelloWorld',
      props: {
        msg: String,
      },
      computed: {
        ...mapGetters({
          list: 'reservations',
        }),
      },
    
      methods: {
        ...mapMutations({
          setList: MUTATIONS.SET_RESERVATIONS,
        }),
      },
    }
    </script>
    
    • 위와 같이 사용 가능
    • options API를 사용하여 우리가 사용할 composition API와는 다소 상이

    SCSS 적용

    $ npm add -D sass
    
    • 위의 명령어로 sass를 npm에 추가
    • 이후 vue component의 style 태그에 다음과 같이 추가
    <style lang="scss">
    </style>
    

    Tip: style에 적용한 것이 전역에 적용되는데요?

    style 태그에 scope를 추가하면 해당 컴포넌트를 루트로 하여 스타일이 적용

    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다