Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Mix lazy load components from vue files

Tags:

webpack

vue.js

im trying to load components from files rather than defining them within the app.js, but I also want to lazy load them, so trying to mix the 2 together.

So a lazy loaded component definiton would look like so:

Vue.component(
    'carousel', 
    () => import(
        /* webpackChunkName: "carousel" */
        './components/carousel.vue'
    )
);

And registering the components using the files is like so:

const files = require.context('./', true, /\.vue$/i);
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

How can I combine this?

My current attempt is as follows, but of course I have missed out the webpackChunkName as no idea how to do that:

const files = require.context('./', true, /\.vue$/i);
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], () => import(files(key)) ));

This doesn't work however, I just get an error saying:

WARNING in ./resources/js/app.js 9:11-29 Critical dependency: the request of a dependency is an expression @ multi ./resources/js/app.js ./resources/sass/index.sass

like image 328
Martyn Ball Avatar asked Apr 19 '20 22:04

Martyn Ball


1 Answers

Ended up using the below code. I think after looking at it, it is similar to what Excalibaard posted, but I couldn't get that to work for me:

const files = require.context('./components', true, /\.vue$/i, 'lazy');
files.keys().map(key => {    
    const name = key.split('/').pop().split('.')[0];
    Vue.component(name, () => import(/* webpackChunkName: "[request]" */'./components/' + key.slice(2)));
});
like image 101
Martyn Ball Avatar answered Nov 15 '22 05:11

Martyn Ball