Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import all Vue components from a folder?

I am trying to load all my vue's components automatically from a folder, which is working fine if I don't use vue "Async Components".

Once I try to use Async Components with import .. I get this error:

10:11-36 Critical dependency: the request of a dependency is an expression

My code that load all components, which generate this error:

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

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => import(componentFilePath));

});

How to fix this ? or is there is any other way to accomplish this?

like image 557
rook99 Avatar asked Jan 24 '19 10:01

rook99


2 Answers

Ok, I needed to add 'lazy' in:

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

and then:

Vue.component(componentName, () => ComponentContext(componentFilePath));
like image 129
rook99 Avatar answered Nov 15 '22 12:11

rook99


I had to merge the question with an answer here to get this final solution:

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

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => ComponentContext(componentFilePath));

});

The 'lazy' third param was added to require.context(), and () => import() was changed to () => ComponentContext().

I can see the bundles in the Network tab of the dev tools pane, and I don't see the bundles when I navigate to a page that doesn't render any of the auto-loaded components.

Therefore, I am reasonably-certain the above code is autoloading and dynamic importing. I will also confirm that in my project, I am using:

require.context('~/components/common', true, /\.vue$/i, 'lazy')

Note where mine is different at ~/components/common compared to ./. Your project needs will likely be different. In mine, the ~ is a Webpack alias for /resources/js, so my full path would be ./resources/js/components/common. The rest of the code above is an algorithm, and can remain untouched.

like image 33
agm1984 Avatar answered Nov 15 '22 12:11

agm1984