Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 525
Stephan-v Avatar asked Apr 26 '18 08:04

Stephan-v


People also ask

How does Webpack dynamic import work?

Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file.

What does require context do?

You can create your own context with the require. context() function. It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

Is dynamic import cached?

Once a module is fetched dynamically from the server, it is cached permanently on the client and additional requests for the same version of the module will not incur the round-trip request to the server. If the module is changed then a fresh copy will always be retrieved from the server.


1 Answers

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);
  });
});
like image 106
minlare Avatar answered Sep 22 '22 21:09

minlare