본문 바로가기
FrontEnd/Vue 3

[Vue.js] vue3 - vue router 설치, Lazy Loading 설정

by Chaedie 2022. 9. 14.
728x90

서론

Vue3 강의 밖에 없어서 vue3를 기준으로 공부를 시작합니다. 연휴기간 시간이 없었기에 아직 HelloWorld를 벗어나지 못한 상태이지만, 그래도 이제 vue에 대해 알아가고 있으니 좋게 생각해야겠죠?!

vue router 설치

  • vue add router 치면 알아서 설치를 해준다.
  • src 하위에 router, views 폴더가 생긴다.

Lazy Load (비동기 컴포넌트) 구성하기

import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import ContactView from '../views/ContactView.vue';
// import AboutView from '../views/AboutView.vue';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  // {
  //   path: '/about',
  //   name: 'about',
  //   component: AboutView,
  // },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
  },
  {
    path: '/contact',
    name: 'ContactView',
    component: ContactView,
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

  1. About 컴포넌트를 주석처리되어 있는 부분처럼 직접 라우팅 시킬 수도 있고,
  2. 주석 해제 되어 있는 부분 처럼 /About으로 갔을 때만 fetch받을 수 있도록 할 수 있다.
  3. 기존에는 pre-fetch 기능이 default로 true였지만, 현재 버젼에선 false이기 때문에 pre-fetch는 기본적으로 작동하지 않는다. (Pre-fetch : 첫 화면에서 코드 스플리팅 한 부분은 미리 캐쉬에만 올려두고, 라우팅 시 로드한다.)
  • Lazy Loading을 사용하면 아래와 같이 About 라우팅이 될 때 해당 컴포넌트의 소스가 별도로 다운로드 되는것을 확인할 수 있다.
  • 이렇게 하면 첫 페이지 로딩 속도를 줄일 수 있다. 다만 페이지 변경 시엔 해당 코드가 fetch 되어야 하므로 { 첫 화면과 페이지 변경 } 어느 부분에서 loading을 감당할 것인지는 개발자들이 결정해야 하는 사안이다.

Pre-fetch를 사용하고 싶다면

import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
// import ContactView from '../views/ContactView.vue';
// import AboutView from '../views/AboutView.vue';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  // {
  //   path: '/about',
  //   name: 'about',
  //   component: AboutView,
  // },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
  },
  {
    path: '/contact',
    name: 'ContactView',
    component: () => import(/* webpackChunkName: "contact", webpackPrefetch:true */ '../views/ContactView.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;
  • preFetch기능을 사용하고 싶다면, component: () => import(/* webpackChunkName: "contact", webpackPrefetch:true */ '../views/ContactView.vue'), 와 같이 import 내부의 어노테이션에 webpackPrefetch:true로 세팅을 해줘야한다.
  • 그럼 아래와 같이 첫 화면에서 컴포넌트가 미리 캐쉬에 올라간다.

마치며...

Lazy Loading이라는 것은 웹앱이라면 당연히 필요한 기능이다. SPA 특성상 첫화면 로딩이 커지는게 당연한 구조이기에 적절한 분산이 필요할것 같다는 생각은 React를 처음 배울 때, SPA 개념 자체를 처음 배울 때 부터 너무 무거워지는게 아닌지 궁금했었고, 질문을 했었던 부분이다. 그 당시 멘토님은 지금 레벨에선 어려울 수 있으니 바벨이나 웹팩이라는 키워드만 가져가라고 말씀을 하셨었다.

어찌되었건 2번의 팀 프로젝트를 React로 구성하면서 Lazy Loading 관련한 부분은 전혀 고려하지 않고 사용했었다. 그래서 어떻게 해야 구현되는지 전혀 감이 안온다. React에서는 Lazy Loading을 어떻게 구현하는건지도 찾아봐야겠다. vue에선 시작부터 가르쳐주는게 뭔가 실용적이고 신선한 느낌이다.

댓글