首页 > 解决方案 > 是否可以使用 `require.context` 为 Webpack 进行动态导入?

问题描述

我目前正在使用require.context加载.vue文件名不以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);
    });
};

现在我想加载Asyncrequire.context

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

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

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

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

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

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

标签: javascriptwebpackvue.jsvue-componentdynamic-import

解决方案


还有第四个论点可以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);
  });
});

推荐阅读