解決Vite無法分析出動態(tài)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) { // 根據(jù)路徑導入組件 const component = await import(path) // 注冊組件 app.use(component.default) } app.mount('#app')
分析
這個錯誤提示來自 Vite 的 import 分析插件:
這個錯誤是因為 Vite 無法分析出上面動態(tài) import 的類型,因為它是以變量的形式,而不是字面量形式寫的。
根據(jù)提示,可以通過以下兩種方式修復:
- 1.將動態(tài)導入路徑改寫為字面量,如
import('./component/xx')
- 2.在 import 語句后面添加:
/* @vite-ignore */
忽略這個 warning
因為我需要動態(tài)引入, 所以我使用第二種方式忽略警告,因為路徑需要動態(tài)生成,無法寫成字面量。
解決方案
在 import 語句后面添加:/* @vite-ignore */
忽略這個 warning
... // 自動注冊全局組件 const modules = import.meta.glob('./components/**/index.ts') for (const path in modules) { // 根據(jù)路徑導入組件 const component = await import(/* @vite-ignore */path) // 注冊組件 app.use(component.default) } ...
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue項目之webpack打包靜態(tài)資源路徑不準確的問題
這篇文章主要介紹了vue項目之webpack打包靜態(tài)資源路徑不準確的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04Vue.js第一天學習筆記(數(shù)據(jù)的雙向綁定、常用指令)
這篇文章主要為大家分享了Vue.js第一天的學習筆記,包括數(shù)據(jù)的雙向綁定、常用指令學習,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12如何用webpack4帶你實現(xiàn)一個vue的打包的項目
這篇文章主要介紹了如何用webpack4帶你實現(xiàn)一個vue的打包的項目,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06