[Vue] router 설정으로 페이지 미리 cache에 담아두기(webpackChunkName, webpackPrefetch)

쿼카쿼카·2022년 10월 22일
0

Vue / Nuxt

목록 보기
2/35

src/App.vue

<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view/>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

src/router/index.js

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

const routes = [
  {
    path: '/',
    name: 'home',
    // 메인 화면은 위에서 import 후 그대로 가져옴
    component: HomeView
  },
  {
    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.
    // webpackChunkName은 network에서 보일 js 파일 이름
    // 이동하는 순간에 받아와도 될 정도로 사이즈가 작은 페이지는 webpackPrefetch 사용 안 함
    // 사이즈가 크고, 접속할 확률이 높은 페이지는 webpackPrefetch: true
    component: () => import(/* webpackChunkName: "about", webpackPrefetch: true */ '../views/AboutView.vue')
  }
]

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

export default router

routes

각 페이지마다 설정

  • path
    • 경로
    • App.vue의 router-link의 to 경로와 일치해야함
  • name
    • 알아보기 쉽도록 설정
  • component
    • 가져올 컴포넌트
    • react로 치면 Route의 element

component

webpackChunkName: ''

  • network에서 js 파일 이름 설정
  • about일 때
  • about10 일 때

webpackPrefetch: true

  • 다른 페이지 컴포넌트를 홈 화면에서 미리 받아 캐시에 담아둠
  • 해당 페이지 열릴 때 시간 절약
  • 첫 페이지에서 시간이 더 소요될 수 있음
  • webpackPrefetch가 없을 때
  • webpackPrefetch: true 일 때

    • 홈 화면에서 이미 prefetch 되어 elements에서도 보이고 about 들어갔을 때 시간도 줄어듬

import하는 3가지 방법

  1. 홈 화면은 위에서 import 후 컴포넌트 이름 그대로 넣음
  2. 이동하는 순간에 받아와도 될 정도로 사이즈가 작은 페이지는 webpackPrefetch 사용 안 함
    • 금방 받아올 수 있는 내용을 처음부터 캐싱해두면 메모리 낭비
  3. 사이즈가 크고, 접속할 확률이 높은 페이지는 webpackPrefetch: true로 미리 캐시에 넣어둠
    • 첫 화면에서 로딩시간이 생기겠지만 해당 페이지로 넘어갈 때는 빠르게 넘어갈 수 있음
profile
쿼카에요

0개의 댓글