0
votes

I am trying to use this techniqe. In short I am trying code splitting with auto-registered dynamically imported Vue components. My file structure is js/utils/vue.js and js/components/***.vue.

This is how my Vue components are loaded:

const files = require.context('../components', true, /\.vue$/i, 'lazy').keys();
files.forEach(file => {
    Vue.component(file.split('/').pop().split('.')[0], () => import(`${file}`));
});

But it results in an error:

[Vue warn]: Failed to resolve async component: function () { return webpack_require("./resources/js/utils lazy recursive ^.*$")("".concat(file)); } Reason: Error: Cannot find module './MainNavbar.vue'

Manually registering the component, while still using dynamic import works. Vue.component('main-navbar', () => import('../components/MainNavbar.vue'));

Why am I receiving this error?

1

1 Answers

1
votes

edit:

I found something here that works for me:

const files = require.context('./', true, /\.vue$/i, 'lazy').keys();

files.forEach(file => {
    Vue.component(file.split('/').pop().split('.')[0], () => import(`${file}`));
});

Judging from the error message, your expression () => import(${file}) needs to prepend the context path, since you're not referencing that like in () => import('../components/MainNavbar.vue')

so maybe something like

const componentName = key.split('/').pop().split('.')[0]
Vue.component(file.split('/').pop().split('.')[0], () => import(`../components/${file}`));

works?