A
A
Artem00712018-12-27 16:13:45
JavaScript
Artem0071, 2018-12-27 16:13:45

Require.context and lazy-loading?

There is a folder with files:
- first.vue
- second.vue
- third.vue
- index.js
index.js:

THIS IS A MAGIC
const context = require.context('./', false, /\.vue$/i)
export default context.keys().reduce((modules, path) => ({
    ...modules,
    [/[a-z]+/i.exec(path).pop()]: context(path).default,
}), {})

Thus, in a separate component, you can get all the components from this folder in this way:
import someComponents from '../pathWithComponents/index.js'

    export default {
        components: {
            ...someComponents
        },

This is magic for me now. I have been trying to understand this small script for a long time, but I still hit my ceiling and cannot fully understand it.
But now we need to remake this into such a script so that lazy-loading can be connected.
I used to do it like this:
components: {
            someComponent: () => import('./pathWithComponents/someComponent')
        },

As a result, everything was loaded only when necessary
. Is it possible to somehow connect these two things? So that they are loaded only when necessary and that you can connect that magic script
Or is it simply technically impossible to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
fl3nkey, 2018-12-27
@Artem0071

Here is the documentation

const requireComponents = {};
const requireComponentContext = require.context('./', false, /\.vue$/i, 'lazy'); //lazy!
requireComponentContext.keys().forEach((fileName, index) => {
  //componentName может быть по названию файла, смотрите пример в документации.
  const componentName = `MySuperComponent-${index + 1}`;
  const componentConfig = requireComponentContext(fileName);
  requireComponents[componentName] = () => componentConfig;
});

//vue instance
export default {
  components: {
    ...requireComponents
  }
}

<my-super-component-1></my-super-component-1>
<my-super-component-2></my-super-component-2>
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question