快速 + 查看路由器 - 动态导入

Vite + Vue Router - Dynamic Imports

我正在将 Vite 与 Vue 3 一起用于个人项目,并且 vue-router@4 用于我的路线。因为我的每个模块都使用同一组路由,所以我创建了一个辅助函数:

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`),
        },
    ]
}

我面临的问题是 Vite 似乎不支持动态导入。

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

我查看了提供的 link 以了解限制,但我的模式似乎与支持的模式相匹配。

为什么我的代码不起作用?一切似乎都很好,但我收到上述警告(当我尝试使用动态导入访问任何路由时,控制台出现错误)。

如果有帮助,我在控制台中得到的错误是:

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

更新: Vite 3.x(目前3.0.0-alpha.7)现在支持动态导入中的别名。你可以安装它:

npm i -D vite@alpha

demo (Vite 3)


邀请 2.x: 您的代码不起作用,因为导入路径违反了这条规则:

Imports must start with ./ or ../.

@ 替换为已解析的路径应该可以解决问题。假设 @<projectRoot>/src 的别名并且 router.js<projectRoot>/src 中,您可以将 @ 替换为 ./:

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`),
  },                         
]

demo (Vite 2)