Skip to content

시작하기

Vue Router에는 내장 파일 기반 라우팅 플러그인이 포함되어 있습니다. 페이지 컴포넌트로부터 라우트와 타입을 자동으로 생성하므로, 더 이상 routes 배열을 수동으로 관리할 필요가 없습니다.

설정

번들러에 플러그인을 추가하세요:

ts
import VueRouter from 'vue-router/vite'

export default defineConfig({
  plugins: [
    VueRouter({
      /* 옵션 */
    }),
    // ⚠️ Vue는 반드시 VueRouter() 뒤에 와야 합니다
    Vue(),
  ],
})
ts
import VueRouter from 'vue-router/unplugin/rollup'

export default {
  plugins: [
    VueRouter({
      /* 옵션 */
    }),
    // ⚠️ Vue는 반드시 VueRouter() 뒤에 와야 합니다
    Vue(),
  ],
}
ts
module.exports = {
  /* ... */
  plugins: [
    require('vue-router/unplugin/webpack')({
      /* 옵션 */
    }),
  ],
}
ts
module.exports = {
  configureWebpack: {
    plugins: [
      require('vue-router/unplugin/webpack')({
        /* 옵션 */
      }),
    ],
  },
}
ts
import { build } from 'esbuild'
import VueRouter from 'vue-router/unplugin/esbuild'

build({
  plugins: [VueRouter()],
})

이 플러그인을 추가한 뒤에는 개발 서버를 시작(보통 npm run dev)하여 typed-router.d.ts타입의 첫 버전을 생성 해야 합니다. 그리고 이 파일을 "moduleResolution": "Bundler"와 함께 tsconfig.json에 추가해야 합니다. 예시는 다음과 같습니다:

json
{
  "include": [
    // 다른 파일들...
    "./typed-router.d.ts"
  ],
  "compilerOptions": {
    // ...
    "moduleResolution": "Bundler",
    // ...
  }
}
ts
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// vue-router가 생성한 파일입니다. ‼️ 이 파일을 수정하지 마세요 ‼️
// 이 파일은 커밋하는 것이 권장됩니다.
// 이 파일을 tsconfig.json의 "includes" 또는 "files" 항목에 추가하세요.

declare module 'vue-router/auto-routes' {
  import type {
    RouteRecordInfo,
    ParamValue,
    ParamValueOneOrMore,
    ParamValueZeroOrMore,
    ParamValueZeroOrOne,
  } from 'vue-router'

  /**
   * vue-router 파일 기반 라우팅이 생성한 라우트 이름 맵
   */
  export interface RouteNamedMap {
    '/': RouteRecordInfo<
      '/',
      '/',
      Record<never, never>,
      Record<never, never>,
      | never
    >
    '/about': RouteRecordInfo<
      '/about',
      '/about',
      Record<never, never>,
      Record<never, never>,
      | never
    >
    '/users/[id]': RouteRecordInfo<
      '/users/[id]',
      '/users/:id',
      { id: ParamValue<true> },
      { id: ParamValue<false> },
      | never
    >
  }
}

Volar 플러그인

Single File Component에서 최상의 TypeScript 경험을 얻으려면 다음 Volar 플러그인을 tsconfig.json(또는 tsconfig.app.json)에 추가하세요:

jsonc
{
  "vueCompilerOptions": {
    "plugins": [
      "vue-router/volar/sfc-route-blocks",
      "vue-router/volar/sfc-typed-router",
    ],
  },
}
  • vue-router/volar/sfc-route-blocks — SFC에서 <route> 블록을 활성화해 페이지별 라우트 메타데이터를 정의할 수 있게 합니다
  • vue-router/volar/sfc-typed-router — 현재 페이지 컴포넌트를 기반으로 useRoute()가 타입 지정된 라우트를 반환하게 하므로 route.params가 올바르게 타입 지정됩니다

기존 프로젝트 마이그레이션

페이지 컴포넌트를 src/pages로 옮기고 그에 맞게 이름을 바꾸세요. 아래는 마이그레이션 예시입니다. 다음과 같은 라우트 구성이 있다고 가정해 봅시다:

ts
import { createRouter, createWebHistory } from 'vue-router'
import { routes, handleHotUpdate } from 'vue-router/auto-routes'

export const router = createRouter({
  history: createWebHistory(),
  routes: [ 
    { 
      path: '/', 
      component: () => import('src/pages/Home.vue'), 
    }, 
    { 
      path: '/users/:id', 
      component: () => import('src/pages/User.vue'), 
    } 
    { 
      path: '/about', 
      component: () => import('src/pages/About.vue'), 
    }, 
  ] 
  routes, 
})

// 페이지를 다시 로드하지 않고 런타임에 라우트를 업데이트합니다
if (import.meta.hot) { 
  handleHotUpdate(router) 
} 
ts
import { createApp } from 'vue'
import { router } from './router'
import App from './App.vue'

createApp(App).use(router).mount('#app')
  • src/pages/Home.vuesrc/pages/index.vue로 이름 변경
  • src/pages/User.vuesrc/pages/users/[id].vue로 이름 변경
  • src/pages/About.vuesrc/pages/about.vue로 이름 변경

파일 규칙 가이드에서 명명 규칙에 대한 자세한 정보를 확인하세요.

처음부터 시작하기

  • src/pages 폴더를 만들고 그 안에 index.vue 컴포넌트를 추가하세요. 이렇게 하면 홈 페이지가 /에서 렌더링됩니다.
  • vue-router/auto-routes에서 routes를 import하여 createRouter 함수에 전달하세요.
ts
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'
import App from './App.vue'

const router = createRouter({
  history: createWebHistory(),
  routes,
})

createApp(App)
  .use(router)
  .mount('#app')
vue
<template>
  <h1>Home</h1>
</template>

파일 규칙 가이드에서 명명 규칙에 대한 자세한 정보를 확인하세요.

라우트 조작하기

routes를 수정이 필요한 어떤 플러그인에든 전달할 수 있지만, 이 변경은 타입에 반영되지 않는다는 점에 주의하세요. 타입 지원을 원한다면 대신 빌드 시점 라우트를 사용하세요. 아래는 Vitesse starter 예시입니다:

ts
import { ViteSSG } from 'vite-ssg'
import { setupLayouts } from 'virtual:generated-layouts'
import App from './App.vue'
import type { UserModule } from './types'
import generatedRoutes from '~pages'
import { routes } from 'vue-router/auto-routes'

import '@unocss/reset/tailwind.css'
import './styles/main.css'
import 'uno.css'

const routes = setupLayouts(generatedRoutes) 

// https://github.com/antfu/vite-ssg
export const createApp = ViteSSG(
  App,
  {
    routes, 
    routes: setupLayouts(routes), 
    base: import.meta.env.BASE_URL,
  },
  ctx => {
    // `modules/` 아래의 모든 모듈을 설치합니다
    Object.values(
      import.meta.glob<{ install: UserModule }>('./modules/*.ts', {
        eager: true,
      })
    ).forEach(i => i.install?.(ctx))
  }
)

ESLint

ESLint를 사용한다면 ESLint 섹션을 확인하세요.

모두를 위한 문서 한글화