Vite + Vue3 + TypeScript 세팅하기

Vincent·2022년 9월 6일
1
post-thumbnail

0. 왜 Vite를 사용해야하는가?

0-1. Vite의 장점은 무엇인가?

  • 빠르다.
  • 서버가 실행된 상태에서도 새로운 패키지를 설치하고 이를 반영할 수 있다.

0-2. Vite의 단점은 무엇인가?

개발 서버에서 작업을 할 때 타입 체킹(Type Checking)이 되지 않는다. 때문에 프로젝트를 빌드할 때 타입 체킹이 되는 불편함이 있다. 최근에는 IDE 자체적으로 타입 체킹을 해주긴 하지만 상황에 따라 이슈를 발생시킬 수 있는 부분이다.

1. Vite 프로젝트 생성하기

$ npm create vite@latest hello-vite

2. Vite 프로젝트 환경 설정하기

2-1. “@” 경로 설정하기

vue-cli로 프로젝트를 생성했을 때는 당연하게 “@”를 통해서 src 폴더의 리소스에 접근하였는데 vite로 프로젝트를 생성하니 이를 따로 설정해줘야하는 부분이라는 것을 알게 되었다.

추후에 찾아보니 이를 간편하게 해주는 패키지도 있는 것을 발견하였다.

2-1-1. @types/node 설치

$ npm install --save-dev @types/node

해당 패키지는 Node.js를 위한 타입 정의 패키지이다. 이를 통해 dirname, filename, path 등에 대한 타입 추론이 가능해진다.
+ @types/* 파일은 ‘dependencies’에 설치해야할까? ‘devDependencies’에 설치해야할까?

2-1-2. vite.config.ts 설정

#001 method

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "url";

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) },
  },
});

#002 method

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import * as path from "path";

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: { "@": path.resolve(__dirname, "./src") },
  },
});

Vite의 설정파일인 vite.config.ts에서 resolve.alias를 통해서 해당 경로를 인식할 수 있게 설정해준다. 위 두가지 코드 모두 정상적으로 작동한다. 1번 방법이 최근 날짜로 리서치된 방법인데 두 방법이 어떤 차이가 있는지는 추후 조사가 필요하다.

하지만 아직 예전처럼 @를 입력 후 자동완성을 눌렀을 때 vscode에서 src 폴더의 하위 리소스가 읽어오지 못하고 있어 추가 설정을 해야겠다.

🔗 참고자료
Import Aliases in Vite
Vue3 - Vite project alias src to @ not working

2-1-3. tsconfig.json 설정

ts파일을 컴파일할 때 “@”를 인식하게 해주기 위해서는 tsconfig.json 파일을 수정해야했다.

{
  "compilerOptions": {
		...,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

이후 vscode에서 “@/” 작성시 자동완성을 하였을 때 src 폴더의 하위 리소스가 나오는 것을 확인할 수 있었다.

2-2. Vite 프로젝트 Eslint & Prettier 적용하기

이 부분도 마찬가지로 vue-cli를 활용해서 프로젝트를 만들었을 때는 당연하게 설치가 되어있는 부분이여서 그 중요성과 이유를 알지 못했다. 평소에 항상 왜 해당 프로그램을 vscode의 확장프로그램으로 다운받고, 추가적으로 npm 패키지도 다운받아야 하는지도 너무나 궁금했다.

이 글에서는 Vite에 적용하는 부분만 다루기 때문에 두개에 대해서 알고 싶은 분들은 아래 링크를 참고 하길 바란다. 정말 깔끔하고 세세하게 정리되어있기에 꼭 시간을 내어 읽고 보았으면 좋겠다.

이번 기회에 이 두가지가 어떤 목적이고, 왜 같이 쓰며, 이에 대한 설정을 어떻게 해야하는지 알게 되는 좋은 기회였다.

🔗 참고자료
ESLint, Prettier Setting, 헤매지 말고 정확히 알고 설정하자.
린트(ESLint)와 프리티어(Prettier)로 협업 환경 세팅하기
ESLint and Prettier with Vite and Vue.js 3

2-2-1. 필요한 패키지 설치하기

$ npm install -D prettier
$ npm install -D eslint
$ npm install -D eslint-plugin-vue
$ npm install -D eslint-config-prettier
$ npm install -D @vue/eslint-config-typescript

2-2-2. .eslint.js 파일 작성하기

module.exports = {
  env: {
    node: true
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'prettier'
  ],
  rules: [
    // override or add rules settings here
  ]
};

3. Vuex 세팅하기

이제는 Pinia를 이용하자. 타입추론, 코드 간결성 등 훨씬 장점이 많다. 나아가 Pinia를 아예 Vuex 5라고 부른다.

3-1. Vuex 설치하기

$ npm install vuex

3-2. Vuex 연결하기

🔗 참고자료
Vuex official website - TypsScript support

3-2-1. src/store/index.ts 파일 생성

import { InjectionKey } from "vue";
import { createStore, useStore as baseUseStore, Store } from "vuex";

export interface State {
  count: number;
}

export const key: InjectionKey<Store<State>> = Symbol();
// vue 컴포넌트에서 store 내부의 state에 대한 타입을 추론하게 해준다.

export default createStore<State>({
  state() {
    return {
      count: 0,
    };
  },
  mutations: {
    increment(state) {
      state.count++;
    },
  },
});

export const useStore = () => {
  return baseUseStore(key);
};

3-2-2. main.ts에 플러그인 추가

import { createApp } from "vue";
import App from "./App.vue";
import store, { key } from "./store";

createApp(App).use(store, key).mount("#app");

3. Pinia 세팅하기

3-1. Pinia 설치하기

$ npm install pinia

3-2. Pinia 플러그인 추가하기

import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from '@/App.vue';

const pinia = createPinia();

createApp(App).use(pinia).mount('#app');

4. Vue-Router 세팅하기

4-1. Vue-Router 설치하기

$ npm install vue-router

4-2. Vue-Router 연결하기

참고자료
Vue Router official website

추가적으로 공식 홈페이지에서 TypeScript을 적용시키는 방법에 대해서는 아직 업데이트가 되어 있지 않아서 vue-cli로 설치할 때 세팅되는 것을 참조하여 코드를 작성하였다.

4-2-1. src/router/index.ts 파일 생성

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/about",
    component: () => import("../views/About.vue"),
  },
];

export default createRouter({
  history: createWebHistory(),
  routes,
});

4-2-2. main.ts에 플러그인 추가

import { createApp } from "vue";
import App from "./App.vue";
import store, { key } from "./store";
import router from "./router";

createApp(App).use(store, key).use(router).mount("#app");
profile
steady

1개의 댓글

comment-user-thumbnail
2022년 11월 24일

감사합니다 ! :>

답글 달기