是否可以使用 `require.context` 为 Webpack 进行动态导入?

Is it possible to use `require.context` to do dynamic imports for Webpack?

我目前正在使用 require.context 来加载文件名不以 Async.

结尾的所有 .vue 组件
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);
    });
};

现在我想用 require.context 加载以 Async 结尾的我的组件,这样我就不必在创建这种类型的新组件时手动添加它们。

通常动态导入语法如下所示:

Vue.component('search-dropdown', () => import('./search/SearchDropdownAsync'));

这将通过承诺得到解决并动态导入组件。

出现的问题是当你使用require.context时,它会立即加载(需要)组件,我无法使用动态导入。

有什么方法可以将require.context和Webpack的动态导入语法结合起来吗?

https://webpack.js.org/guides/code-splitting/#dynamic-imports

require.context 有第四个参数可以帮助解决这个问题。

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);
  });
});