Search code examples
vue.jsvue-routervue-cli

Default vue-cli lazy load code for route does not work when defined as lambda


I used vue-cli to scaffold a new Typescript project and specified it should include vue-router.

This auto-generated a router/index.ts with a router configuration that looked like this:

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
 },
  {
    path: '/about',
    name: 'About',
    component: () => { import(/* webpackChunkName: "about" */ '../views/About.vue') },
  }
]

This file compiles fine as one would expect. However, when I try to call the route using <router-link> the About page does not render. I can confirm the route is being called, because if I add a console.log('x') into the import lambda above, I see the 'x' in the console but the About component constructor is never called and the About content is not rendered.

However, if I adjust the index.ts as follows (as per docs), then the route works correctly and displays the view:

const AboutRoute = () => import('../views/About.vue')

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
 },
  {
    path: '/about',
    name: 'About',
    component: AboutRoute,
  }
]

Can anyone explain why the second version works, but not the first as they seem equivalent to me.

Thanks Ian


Solution

  • Your 1st solution doesn't work because it's not returning the import.

    In Javscript when you add brackets { } to a function, it's not going to return the result automatically, you need to add the return word yourself. So either don't add brackets or add return:

    Method 1:

    component: () => {
      return import(
        /* webpackChunkName: "about" */ 
        '../views/About.vue'
      )
    }
    
    

    Method 2:

    component: () => import(
      /* webpackChunkName: "about" */ 
      '../views/About.vue'
    )