时间:2023-02-23 09:11:08 | 栏目:vue | 点击:次
在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为:
vue-router.esm.js:1793 Error: Loading chunk 3 failed.
查看加载的路径时 /a/3.hash.js 找不到;
很可能是静态资源路径根未指定,相对路径相对于当前url目录导致,修改:
//webpack.config.js config.output.publicPath = '/';
最近在使用VueRouter的懒加载组件的时候.
const routes = [
{
path: '/',
component: App
},
{
path: '/category',
component: resolve => {require(['./components/Category.vue'], resolve)}
}
]
但是在加载/category的时候,我发现会报错。
原来webpack会把这个懒加载单独加载一个js,默认按照
0.app.js 1.app.js ……的顺序加载的
通过简单的debug发现是0.app.js的路径不对
通过webpack的设置即可解决(我使用的laravel,配置根据情况自行修改)
Elixir.webpack.mergeConfig({
module: {
loaders: [
{
test: /\.css/,
loader: "style!css"
}
]
},
output: {
publicPath: "js/"
}
})
配置下output下的publicPath即可。