目前我使用require.context
加载所有的Vue组件,它会在我的components
目录中查找以.vue
为后缀的文件。这个方法可以正常工作,但是我也想用动态导入来加载异步组件。
但是使用require.context
时,所有的文件都会被加载,即使我想要使用动态导入,文件已经被加载了,所以什么都不会发生。
我需要一种方式从require.context
调用中排除某些文件。因为这种方式无法与require.context
动态创建正则表达式。
// How I currently load my Vue components.
const components = require.context('@/components', true, /[A-Z]\w+\.vue$/);
components.keys().forEach((filePath) => {
const component = components(filePath);
const componentName = path.basename(filePath, '.vue');
// Dynamically register the component.
Vue.component(componentName, component);
});
// My component that I would like to load dynamically.
Vue.component('search-dropdown', () => import('./search/SearchDropdown'));
看起来唯一的方法是手动声明我所有的组件,这很麻烦。
或者创建一个静态正则表达式,跳过文件名中带有Async
的文件。这强制我采用一定的异步组件命名约定,也不是理想的选择。
是否有更好的方法来处理这个问题?