vue?懶加載組件chunk相對路徑混亂問題及解決
懶加載組件chunk相對路徑混亂問題
問題描述
在vue項目中用vue-router做路由,做代碼分割和懶加載時,由于webpack配置不當(dāng),導(dǎo)致懶加載chunk時相對路徑出現(xiàn)混亂導(dǎo)致加載chunk失敗
具體如下
//router.js
import VueRouter from 'vue-router'
const A = () => import('./pages/a.vue');
const B = () => import('./pages/b.vue');
const AA = () => import('./pages/a.a.vue');
const AB = () => import('./pages/a.b.vue');
const routes = [
? ? {
? ? path: '/a', component: A,children:[{
? ? ? ? path:'a', component:AA
? ? },{
? ? ? ? path:'b', component:AB
? ? }]
},?
{
? ? path: '/b/:id', component: B, props: true
}]
const router = new VueRouter({
? ? mode: 'history',
? ? routes
})
export default router;如上路由配置,編譯之后對應(yīng)的chunk為:
- A —- 0.hash.js
- B —- 1.hash.js
- AA —- 2.hash.js
- AB —- 3.chunk.js
- 當(dāng) url 為 /a 或 /b時正常,且兩者可以自由切換;
- 當(dāng)從 /a 切換為 /a/a 或 /a/b時也正常;
- 當(dāng)從/a/a 切換為 /a/b時報錯
vue-router.esm.js:1793 Error: Loading chunk 3 failed.
查看加載的路徑時 /a/3.hash.js 找不到;
解決方法
很可能是靜態(tài)資源路徑根未指定,相對路徑相對于當(dāng)前url目錄導(dǎo)致,修改:
//webpack.config.js config.output.publicPath = '/';
懶加載組件 路徑不對
最近在使用VueRouter的懶加載組件的時候.
const routes = [
? ? {
? ? ? ? path: '/',
? ? ? ? component: App
? ? },
? ? {
? ? ? ? path: '/category',
? ? ? ? component: resolve => {require(['./components/Category.vue'], resolve)}
? ? }
]
但是在加載/category的時候,我發(fā)現(xiàn)會報錯。
原來webpack會把這個懶加載單獨加載一個js,默認按照
0.app.js 1.app.js ……的順序加載的
通過簡單的debug發(fā)現(xiàn)是0.app.js的路徑不對
通過webpack的設(shè)置即可解決(我使用的laravel,配置根據(jù)情況自行修改)
Elixir.webpack.mergeConfig({
? ? module: {
? ? ? ? loaders: [
? ? ? ? ? ? {
? ? ? ? ? ? ? ? test: /\.css/,
? ? ? ? ? ? ? ? loader: "style!css"
? ? ? ? ? ? }
? ? ? ? ]
? ? },
? ? output: {
? ? ? ? publicPath: "js/"
? ? }
})配置下output下的publicPath即可。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
element UI 中的 el-tree 實現(xiàn) checkbox&n
在日常項目開發(fā)中,會經(jīng)常遇到,樹形結(jié)構(gòu)的查詢方式,為了快速方便開發(fā),常常會使用到快捷的ui組件去快速搭樹形結(jié)構(gòu),這里我用的是 element ui 中的 el-tree,對element UI 中的 el-tree 實現(xiàn) checkbox 單選框及 bus 傳遞參數(shù)的方法感興趣的朋友跟隨小編一起看看吧2022-09-09
vue報錯之exports is not defined問題的解決
這篇文章主要介紹了vue報錯之exports is not defined問題的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Vue 中v-model的完整用法及v-model的實現(xiàn)原理解析
這篇文章詳細介紹了Vue.js中的v-model指令的使用,包括基本用法、原理、結(jié)合不同類型的表單元素(如radio、checkbox、select)以及使用修飾符(如lazy、number、trim)等,感興趣的朋友一起看看吧2025-02-02

