Vue - 타입 스크립트 개발 환경 구성 및 Serverless Functions

김영준·2023년 8월 13일
0

TIL

목록 보기
83/91
post-thumbnail

개발 환경 구성하기

프로젝트 생성

npm create vite@latest .

패키지 설치

npm i

eslint, prettier 설치

npm i -D eslint prettier eslint-plugin-prettier eslint-config-prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-vue

.eslintrc.json

{
  "extends": [
    "eslint:recommend",
    "plugin:@typescript-eslint/recommended",
    "plugin:vue/vue3-recommended",
    "plugin:prettier/recommended"
  ],
  "parserOptions": {
    "parser": "@typescript-eslint/parser"
  }
}

.prettierrc

{
  "semi": false,
  "singleQuote": true,
  "endOfLine": "lf",
  "singleAttributePerLine": true,
  "bracketSameLine": true,
  "trailingComma": "none"
}

라우터, pinia(상태관리 라이브러리) 설치

npm i vue-router pinia

라우터, pinia 등록

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './routes'
import App from './App.vue'

createApp(App).use(createPinia()).use(router).mount('#app')

라우터 생성

// /src/routes/index.ts

import { createRouter, createWebHistory } from 'vue-router'
import MainPage from './MainPage.vue'

export default createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: MainPage
    }
  ]
})

vercel 서버리스 함수 연결하기

npm i -D vercel

package.json scripts 작성

"scripts": {
    "dev": "vite",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "vercel": "vercel dev"
  },

개발 서버 열기

npm run vercel 

옵션 세팅

루트 경로에 api 폴더 생성 후 todos.ts 파일 생성
서버리스 함수는 nodejs 환경으로 동작하기 때문에 fetch 대신 axios 사용
vercel 서버리스 함수는 dotenv 패키지가 내장되어 있다.

npm i axios
// api/todos.ts

import axios from 'axios'
import type { VercelRequest, VercelResponse } from '@vercel/node'

const { APIKEY, USERNAME } = process.env

interface RequestBody {
  path: '' | 'deletions' | 'reorder'
  method: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data: {
    [key: string]: unknown
  }
}

export default async function (req: VercelRequest, res: VercelResponse) {
  const { path = '', method = 'GET', data } = req.body as Partial<RequestBody>
  const { data: responseValue } = await axios({
    url: `https://URL/${path}`,
    method,
    headers: {
      'content-Type': 'application/json',
      apikey: APIKEY,
      username: USERNAME
    },
    data
  })
  res.status(200).json(responseValue)
}


파일 이름으로 접근 가능, 단 POST로 접근해야 함

async createTodo({ title }: CreateTodoPayload) {
  await axios.post('/api/todos', {
    method: 'POST',
    data: {
      title
    }
  })
}

에러가 발생한다면 typescript의 버전을 맞춰줘야 함
package.json에 아래 옵션 추가 (ts 최신 버전으로)

"overrides": {
    "@vercel/node": {
      "ts-node": "10.9.1",
      "typescript": "5.1.6"
    }
  }

scss 사용하기 위한 세팅

npm i -D sass

경로 별칭 지정하기
vite.config.ts에 resolve 옵션 추가

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{ find: '~', replacement: '/src' }]
  }
})

타입 스크립트에서도 인식할 수 있게 tsconfog.json에 아래 내용 추가


드래그 기능 삽입하기

sortablejs 라이브러리 설치

npm i sortablejs 
npm i -D @types/sortablejs

첫 번째 요소를 지정할 때는 element 타입으로 지정해야 한다.

import Sortable from 'sortablejs'

// 첫 번째 인수는 드래그 요소를 적용 할 요소, 두 번째 인수는 옵션
function initSortable() {
  if (todoListEl.value) {
    new Sortable(todoListEl.value, {
      handle: '.drag-handle', // 드래그 핸들러 요소
      animation: 0, // 애니메이션 효과
      forceFallback: true, // 브라우저에 의존하지 않고 자체적인 드래그 기능을 강제함
      onEnd: (event) => {
        const { oldIndex, newIndex } = event
        todosStore.reorderTodos({
          oldIndex: oldIndex as number,
          newIndex: newIndex as number
        })
      } // 목록의 순서를 바꾼 후 실행되는 함수
    })
  }
}

날짜 데이터를 원하는 포맷으로 변경하기

dayjs 라이브러리 설치

npm i dayjs

import dayjs from 'dayjs'

function formatDate(date: string) {
  return dayjs(date).format('YYYY년 M월 D일 H시 m분')
}

vercel 배포 커밋 만들기

git commit --allow-empty -m "Vercel 재배포용"

Vercel 배포 후 새로고침 문제 해결

하위 경로에서 새로고침을 해도 index.html 파일로 연결이 되게 설정

// vercel.json

{
  "routes": [
    { "handle": "filesystem" },
    { "src": "/(.*)", "dest": "/index.html" }
  ]
}

하지만 vercel과 vitejs의 충돌로 인해 로컬 서버에 문제가 발생한다.


vite.config.ts에 아래 내용 추가

vitejs의 로컬 서버와 vercel의 로컬 서버를 따로 열어서 vitejs의 로컬 서버 기준으로 vercel의 서버리스 함수를 사용할 수 있도록 proxy라는 옵션으로 연결한다.


두 개의 서버를 하나로 관리하기

3000번 포트는 자주 쓰이므로 2999 포트로 변경

server: {
    proxy: {
      '/api': { target: 'http://localhost:2999' }
    }
  }

package.json에 있는 여러개의 스크립트를 동시에 실행시켜줄 수 있는 라이브러리 설치

npm i -D concurrently

package.json의 scripts 수정

"scripts": {
    "dev": "concurrently npm:watch-*",
    "watch-vite": "vite",
    "watch-vercel": "vercel dev --listen 2999",
    "build": "vue-tsc && vite build",
    "preview": "vite preview"
  },

이제 터미널에 npm run dev만 입력해도 watch-로 시작하는 스크립트를 모두 실행한다.

추가로 vitejs의 서버가 중심인 것을 주의해야 한다.

profile
꾸준히 성장하는 개발자 블로그

0개의 댓글