问题
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
回答1:
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);
});
});
来源:https://stackoverflow.com/questions/50038473/is-it-possible-to-use-require-context-to-with-dynamic-imports-for-webpack