SoFunction
Updated on 2025-04-07

vue: Lazy loading component chunk relative path confusion problem and solution

Lazy loading component chunk relative path confusion problem

Problem description

When using vue-router for routing, code segmentation and lazy loading, due to improper configuration of webpack, relative paths when lazy loading chunks are confusing, causing chunks to fail to load chunks due to improper configuration of webpacks.

Specific as follows

//
import VueRouter from 'vue-router'
const A = () => import('./pages/');
const B = () => import('./pages/');
const AA = () => import('./pages/');
const AB = () => import('./pages/');
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;

As shown in the above route configuration, the corresponding chunk after compilation is:

  • A —-
  • B —-
  • AA —-
  • AB —-
  • It is normal when url is /a or /b, and the two can be switched freely;
  • It is also normal when switching from /a to /a/a or /a/b;
  • An error occurred when switching from /a/a to /a/b

:1793 Error: Loading chunk 3 failed.

/a/ cannot be found when viewing the loaded path;

Solution

It is very likely that the static resource path root is not specified, and the relative path relative to the current url directory causes modification:

//
 = '/';

Lazy loading component with wrong path

Recently, I was using VueRouter's lazy loading components.

const routes = [
    {
        path: '/',
        component: App
    },
    {
        path: '/category',
        component: resolve => {require(['./components/'], resolve)}
    }
]

But when loading /category, I found that an error would be reported.

It turns out that webpack will load this lazy load separately with js, and by default

Loaded in order of...

Through simple debugging, I found that the path is wrong.

It can be solved through the settings of webpack (I use laravel, the configuration is modified by myself according to the situation)

({
    module: {
        loaders: [
            {
                test: /\.css/,
                loader: "style!css"
            }
        ]
    },
    output: {
        publicPath: "js/"
    }
})

Just configure the publicPath under output.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.