问题:
在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 的类型,因为它是以变量的形式,而不是字面量形式写的。
根据提示,可以通过以下两种方式修复:
-
将动态导入路径改写为字面量,如
import('./component/xx')
-
在 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)
}
...