1. 程式人生 > >vue 懶載入元件chunk相對路徑混亂問題

vue 懶載入元件chunk相對路徑混亂問題

問題描述
在vue專案中用vue-router做路由,做程式碼分割和懶載入時,由於webpack配置不當,導致懶載入chunk時相對路徑出現混亂導致載入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;

如上路由配置,編譯之後對應的chunk為:
A —- 0.hash.js
B —- 1.hash.js
AA —- 2.hash.js
AB —- 3.chunk.js
當 url 為 /a 或 /b時正常,且兩者可以自由切換;
當從 /a 切換為 /a/a 或 /a/b時也正常;
當從/a/a 切換為 /a/b時報錯

vue-router.esm.js:1793 Error: Loading chunk 3 failed.

檢視載入的路徑時 /a/3.hash.js 找不到;

解決方法
很可能是靜態資源路徑根未指定,相對路徑相對於當前url目錄導致,修改:

//webpack.config.js
config.output.publicPath = '/';