Vue路由器延迟加载在Vite中不起作用(错误:未知变量动态导入)

8yoxcaq7  于 2022-12-30  发布在  Vue.js
关注(0)|答案(3)|浏览(437)

我已经建立了下面的代码在Vue路由器和它的工作完美的Vue-CLI。

import store from "./../../store/index.js";
        
        function getView(view) {
          return () => import(`@/views/settings/${view}.vue`);
        }
        
        const routes = [
          {
            path: "/myProfile",
            name: "MyProfile",
            component: getView("MyProfile"),
            beforeEnter: (to, from, next) => {
              document.title = "Profile - " + store.getters.getAppName;
              if (store.getters["userStore/authenticated"]) {
                next();
              } else {
                next({ name: "Home" });
              }
            },
          }
        ]
        export default routes;

现在我用Vite替换了Vue-CLI,它给出了以下错误。

TypeError: Failed to resolve module specifier '@/views/settings/MyProfile.vue'

当我删除getView(“MyProfile”)函数并直接使用import时,它可以工作,如下所示。

const routes = [
          {
            path: "/myProfile",
            name: "MyProfile",
            component: () => import('@/views/settings/MyProfile.vue'),
            beforeEnter: (to, from, next) => {
              document.title = "Profile - " + store.getters.getAppName;
              if (store.getters["userStore/authenticated"]) {
                next();
              } else {
                next({ name: "Home" });
              }
            },
          }
        ]

有人能解释一下吗?

qq24tv8q

qq24tv8q1#

有人能解释一下吗?
这是由于汇总限制。所有导入必须相对于导入文件开始,并且导入不应以变量开始
因此,要使GetView()函数工作,必须将别名(@/)替换为相对或绝对路径../views/src/views

function getView(view) {
  return () => import(`../views/settings/${view}.vue`);
}

为什么当您删除getView()并直接编写import指令时,它仍然有效?
如果您设置了一个文本字符串,则别名将被解析 (根据汇总要求,它将最终成为相对或绝对路径)

lo8azlld

lo8azlld2#

有点晚,但这应该是你的问题的答案,动态导入在不同的捆绑包肯定会有不同的行为
我们有维特的情况下涵盖的官方文件在这里:https://router.vuejs.org/guide/advanced/lazy-loading.html#with-vite
希望这会有帮助:)

mbyulnm0

mbyulnm03#

在尝试了很多选择之后,我终于找到了这个解决方案。

import store from "./../../store/index.js";
    
    async function getView(view) {
      const comps = import.meta.glob("../views/**/*.vue");
      const match = comps[`../views/${view}.vue`];
      //For TS: const match: () => Promise<any> = comps[`../views/${view}.vue`];

      return (await match()).default;
    }
    
    const routes = [
      {
        path: "/myProfile",
        name: "MyProfile",
        component: () => getView("settings/MyProfile"),
        beforeEnter: (to, from, next) => {
          document.title = "Profile - " + store.getters.getAppName;
          if (store.getters["userStore/authenticated"]) {
            next();
          } else {
            next({ name: "Home" });
          }
        },
      }
    ]
    export default routes;

希望,这将解决问题。(这对任何路线都有效。)

相关问题