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

半城伤御伤魂 提交于 2020-08-24 08:10:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!