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?
Ok, I needed to add 'lazy' in:
const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');
and then:
Vue.component(componentName, () => ComponentContext(componentFilePath));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With