前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue3和vite项目踩炕提示The above dynamic import cannot be analyzed by Vite.

Vue3和vite项目踩炕提示The above dynamic import cannot be analyzed by Vite.

作者头像
岳泽以
发布2022-11-11 20:33:37
5.3K0
发布2022-11-11 20:33:37
举报
文章被收录于专栏:岳泽以博客岳泽以博客

在做一个用vite构建的vue3项目时,动态拉取菜单导入页面,然后一直报错,偶尔可以,偶尔不行。

问题描述

原错代码:

代码语言:javascript
复制
menu.forEach((item) => {
        if (item.children) {
          item.children = item.children.map((item) => {
            let url = `../views/${item.url}.vue`;

            item.component = () => import(url);
            return item;
          });
          menuArray.push(...item.children);
        } else {
          let url = `../views/${item.url}.vue`;
          item.component = () => import(url);
          menuArray.push(item);
        }
      });

报错信息:

代码语言:javascript
复制
16:40:30 [vite] page reload src/store/index.js
16:40:30 [vite] warning: 
E:/manage-app/src/store/index.js
48 |              return item;
49 |            });
50 |            menuArray.push(...item.children);
   |   ^
51 |          } else {
52 |            let url = `../views/${item.url}.vue`;
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: E:/manage-app/src/store/index.js

解决方案

报错提示让我们使用:@rollup/plugin-dynamic-import-vars这个插件。

Vite官方文档说需要使用Glob 导入形式,然后看了一个Glob的文档,解决了这个问题。

首先需要使用特殊的import.meta.glob函数从文件系统导入多个模块:

代码语言:javascript
复制
const modules = import.meta.glob('../views/*/*.vue');

他会匹配并导入所有相关的组件:

代码语言:javascript
复制
// vite 生成的代码
const modules = {
  './views/foo.vue': () => import('./views/foo.vue'),
  './views/bar.vue': () => import('./views/bar.vue')
}

然后修正代码即可:

代码语言:javascript
复制
      menu.forEach((item) => {
        if (item.children) {
          item.children = item.children.map((item) => {
            let url = `../views/${item.url}.vue`;
            item.component = modules[url];
            return item;
          });
          menuArray.push(...item.children);
        } else {
          let url = `../views/${item.url}.vue`;
          item.component = modules[url];
          menuArray.push(item);
        }
      });
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022 年 10 月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题描述
  • 解决方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档