FlyC
FlyC

Reputation: 1874

vue-cli with Webpack: how to custom splitting import chunk?

I'm not sure the title is hit the point or not, I'll try my best to explain:

I have 4 pages, which is a1.vue, a2.vue, b1.vue and b2.vue
my router/index.js:

import a1 from '@/components/a1';  
import a2 from '@/components/a2';  
import b1 from '@/components/b1';  
import b2 from '@/components/b2';  

var router = new Router({  
    routes: [{  
        path: '/a1',  
        name: 'name-a1',  
        component: a1  
    }, {  
        path: '/a2',  
        name: 'name-a2',  
        component: a2  
    }, {  
        path: '/b1',  
        name: 'name-b1',  
        component: b1  
    }, {  
        path: '/b2',  
        name: 'name-b2-page',  
        component: b2  
    }]  
});  

then if I run npm run build, it will render a app.js file, which include my a1~b2 pages' resources.
and I know that if I write this:

const a1 = ()=> import('@/components/a1');  
const a2 = ()=> import('@/components/a2');  
const b1 = ()=> import('@/components/b1');  
const b2 = ()=> import('@/components/b2');  

webpack will render a1.js, a2.js, b1.js, b2.js for me, and only load it when I visit the mapping page.
here is the question:

how to chunk a.js and b.js,
which a.js includes a1.js and a2.js source,
b.js includes b1.js and b2.js source?
and of course, if I visit /a2 after visit /a1, the a.js won't load again.

thx

Upvotes: 3

Views: 4717

Answers (1)

Đorđe Zeljić
Đorđe Zeljić

Reputation: 1825

You can use webpack's special parameters via comments feature.

For example, in your case:

const a1 = ()=> import(/* webpackChunkName: "a" */'@/components/a1');
const a2 = ()=> import(/* webpackChunkName: "a" */'@/components/a2');
const b1 = ()=> import(/* webpackChunkName: "b" */'@/components/b1');
const b2 = ()=> import(/* webpackChunkName: "b" */'@/components/b2');

You also can use webpackMode: lazy.

For more info and examples read: https://webpack.js.org/api/module-methods/

Upvotes: 6

Related Questions