Home > Mobile >  Vite Vue Router - Dynamic Imports
Vite Vue Router - Dynamic Imports

Time:02-02

I'm using Vite together with Vue 3 for a personal project and have vue-router@4 for my routes. Because each of my modules uses the same set of routes, I created a helper function:

import { RouteRecordRaw } from 'vue-router'
import pluralize from 'pluralize'
import Str from '@supercharge/strings'

export function createRoutes(name: string): Array<RouteRecordRaw> {
    const plural = pluralize.plural(name)
    const path = Str(plural).trim().lower().kebab().get()
    const module = Str(plural).trim().studly().get()
    const titleSingular = Str(pluralize.singular(name)).title().get()
    const titlePlural = Str(plural).title().get()

    return [
        {
            path: `/${path}`,
            name: titlePlural,
            component: () => import(`@/views/${module}/index.vue`),
        },
        {
            path: `/${path}/:id`,
            name: titleSingular,
            component: () => import(`@/views/${module}/Single.vue`),
        },
        {
            path: `/${path}/new`,
            name: `New ${titleSingular}`,
            component: () => import(`@/views/${module}/New.vue`),
        },
    ]
}

The problem I'm facing however is that Vite doesn't appear to support dynamic imports.

3:05:29 pm [vite] warning: 
G:/Dev/world-building/client/src/router/util.ts
21 |        path: `/${path}/new`,
22 |        name: `New ${titleSingular}`,
23 |        component: () => import(`@/views/${module}/New.vue`)
   |                                ^
24 |      }
25 |    ];
The above dynamic import cannot be analyzed by vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

  Plugin: vite:import-analysis
  File: G:/Dev/world-building/client/src/router/util.ts

I took a look at the provided link to see the limitations however my pattern appears to match what's supported.

Why doesn't my code work? Everything appears to be fine yet I get the above warning (and an error in console when I try to visit any routes using dynamic imports).

In case it helps, the error I get in console is:

TypeError: Failed to resolve module specifier '@/views/Galaxies/index.vue'

CodePudding user response:

Your code doesn't work because the import paths violate this rule:

Imports must start with ./ or ../.

Replacing @ with the resolved path should fix the problem. Assuming @ is aliased to <projectRoot>/src and router.js is in <projectRoot>/src, you could replace @ with ./:

return [
  {
    path: `/${path}`,
    name: titlePlural,
    component: () => import(`./views/${module}/index.vue`),
  },                                    
  •  Tags:  
  • Related