解決Vite無法分析出動(dòng)態(tài)import的類型,控制臺(tái)出警告的問題
問題
在main.ts中需要自動(dòng)注冊(cè)全局組件
運(yùn)行vite的時(shí)候,控制臺(tái)會(huì)報(bào)警告:
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.
當(dāng)前的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)
// 自動(dòng)注冊(cè)全局組件
const modules = import.meta.glob('./components/**/index.ts')
for (const path in modules) {
// 根據(jù)路徑導(dǎo)入組件
const component = await import(path)
// 注冊(cè)組件
app.use(component.default)
}
app.mount('#app')
分析
這個(gè)錯(cuò)誤提示來自 Vite 的 import 分析插件:
這個(gè)錯(cuò)誤是因?yàn)?Vite 無法分析出上面動(dòng)態(tài) import 的類型,因?yàn)樗且宰兞康男问?而不是字面量形式寫的。
根據(jù)提示,可以通過以下兩種方式修復(fù):
- 1.將動(dòng)態(tài)導(dǎo)入路徑改寫為字面量,如
import('./component/xx') - 2.在 import 語句后面添加:
/* @vite-ignore */忽略這個(gè) warning
因?yàn)槲倚枰獎(jiǎng)討B(tài)引入, 所以我使用第二種方式忽略警告,因?yàn)槁窂叫枰獎(jiǎng)討B(tài)生成,無法寫成字面量。
解決方案
在 import 語句后面添加:/* @vite-ignore */ 忽略這個(gè) warning
...
// 自動(dòng)注冊(cè)全局組件
const modules = import.meta.glob('./components/**/index.ts')
for (const path in modules) {
// 根據(jù)路徑導(dǎo)入組件
const component = await import(/* @vite-ignore */path)
// 注冊(cè)組件
app.use(component.default)
}
...
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- vue3+vite+vant項(xiàng)目下按需引入vant報(bào)錯(cuò)Failed?to?resolve?import的原因及解決方案
- vite添加環(huán)境變量import.meta.env的方法
- vite中的glob-import批量導(dǎo)入的實(shí)現(xiàn)
- Vite3結(jié)合Svelte3使用@import導(dǎo)入scss樣式
- vue3+vite項(xiàng)目中按需引入vant報(bào)錯(cuò):Failed?to?resolve?import的解決方案
- vue3+vite中使用import.meta.glob的操作代碼
- vue3+vite引入插件unplugin-auto-import的方法
相關(guān)文章
element vue Array數(shù)組和Map對(duì)象的添加與刪除操作
這篇文章主要介紹了element vue Array數(shù)組和Map對(duì)象的添加與刪除功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-11-11
vue實(shí)現(xiàn)仿淘寶結(jié)賬頁面實(shí)例代碼
本文是小編給大家分享的vue實(shí)現(xiàn)仿淘寶結(jié)賬頁面實(shí)例代碼,主要功能是仿照淘寶頁面的結(jié)算購物車商品時(shí)自動(dòng)算出合計(jì)價(jià)格的頁面,具體實(shí)例代碼大家參考下本文2017-11-11
vue3?element-plus?實(shí)現(xiàn)表格數(shù)據(jù)更改功能詳細(xì)步驟
這篇文章主要介紹了vue3 element-plus實(shí)現(xiàn)表格數(shù)據(jù)更改功能,本文分步驟結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
Vue中實(shí)現(xiàn)3D標(biāo)簽云的詳細(xì)代碼
本文通過實(shí)例代碼給大家介紹vue實(shí)現(xiàn)3D標(biāo)簽云的方法,代碼簡單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-07-07
vue項(xiàng)目build打包后部分樣式錯(cuò)亂的解決
這篇文章主要介紹了vue項(xiàng)目build打包后部分樣式錯(cuò)亂的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07

