I am currently using require.context
to load all my .vue
components that do not have a filename ending with Async
.
const loadComponents = (Vue) => {
const components = require.context('@/components', true, /\/[A-Z](?!\w*Async\.vue$)\w+\.vue$/);
components.keys().forEach((filePath) => {
const component = components(filePath);
const componentName = path.basename(filePath, '.vue');
// Dynamically register the component.
Vue.component(componentName, component);
});
};
Now I want to load the my components that end with Async
with require.context
so I don't have to manually add them whenever I create a new component of this type.
Normally the dynamic import syntax would look like this:
Vue.component('search-dropdown', () => import('./search/SearchDropdownAsync'));
This will get resolved with a promise and import the component dynamically.
The problem that occurs is that when you use require.context
, it will immediately load(require) the components and I am unable to use the dynamic import.
Is there any way to combine require.context
with the dynamic import syntax of Webpack?
https://webpack.js.org/guides/code-splitting/#dynamic-imports
Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file.
You can create your own context with the require. context() function. It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.
Once a module is fetched dynamically from the server, it is cached permanently on the client and additional requests for the same version of the module will not incur the round-trip request to the server. If the module is changed then a fresh copy will always be retrieved from the server.
There is a fourth argument for require.context
which can help with this.
https://webpack.js.org/api/module-methods/#requirecontext
https://github.com/webpack/webpack/blob/9560af5545/lib/ContextModule.js#L14
const components = require.context('@/components', true, /[A-Z]\w+\.(vue)$/, 'lazy');
components.keys().forEach(filePath => {
// load the component
components(filePath).then(module => {
// module.default is the vue component
console.log(module.default);
});
});
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