【已解决】Vite 无法分析出动态 import 的类型, 控制台出警告

问题:

在main.ts中需要自动注册全局组件
运行vite的时候,控制台会报警告:

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.

当前的vite版本: “vite”: “^4.4.5”
在这里插入图片描述
src\main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import { store, key } from './store'
import elementPlus from './plugins/element-plus'

// 加载全局样式
import './styles/index.scss'
const app = createApp(App)
app.use(router)
app.use(store, key)
app.use(elementPlus)

// 自动注册全局组件
const modules = import.meta.glob('./components/**/index.ts')

for (const path in modules) {
  // 根据路径导入组件
  const component = await import(path)

  // 注册组件
  app.use(component.default)
}
app.mount('#app')

分析:

这个错误提示来自 Vite 的 import 分析插件:
这个错误是因为 Vite 无法分析出上面动态 import 的类型,因为它是以变量的形式,而不是字面量形式写的。

根据提示,可以通过以下两种方式修复:

  1. 将动态导入路径改写为字面量,如 import('./component/xx')

  2. 在 import 语句后面添加:/* @vite-ignore */ 忽略这个 warning

因为我需要动态引入, 所以我使用第二种方式忽略警告,因为路径需要动态生成,无法写成字面量。

解决方案

在 import 语句后面添加:/* @vite-ignore */ 忽略这个 warning

...
// 自动注册全局组件
const modules = import.meta.glob('./components/**/index.ts')

for (const path in modules) {
  // 根据路径导入组件
  const component = await import(/* @vite-ignore */path)

  // 注册组件
  app.use(component.default)
}
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值