Say first

Webpack has a trick: use require.context() to automatically import modules

The official document is a bit abstruse, I took a paragraph to use it directly, but would like to see how it works

This article will not go into too much depth, but a way of reading it helps to understand how it works

Na used the vuex transformation of the random VUE project as an example

We are only studying require.context(), not how to modify vuex.

start

Create a directory structure with 2 modules:

To export anything from a module, we use a simple object:

In store.js, we then copied code that looks like this:

Of course, look at the output first, which looks like this:

In this way, we successfully read the exported module objects in our two files

research

The above code may be a bit confusing, so let’s modify it and break it down into the simplest code to make sense of it, like this:

Require.context () returns a function that prints out the RCFN:

You can click on it (using Chrome), go inside the function and see something like this:

The following module exposes the webpackContext method

This method takes one argument and returns the module loaded using the __webpack_require__ method

And webpackContext also has a keys property, which is a method that returns the key of the map object above

That’s the file under modules + pathname that we called in the above example

So it is clear that we use const moduleKeys = rcfn.keys() to get an array of file names:

Create an empty array and iterate over the file name + path array you got above, bringing in the method RCFN that was originally returned by require.context()

As mentioned above, this method returns a reference to __webpack_require__ to load the module

So we get modules array, which is two elements, each of which contains the default module we exported

Filter with map:

The dissolution of

Require.context () is used to iterate through the file name in the directory and load the module in the file using the file name.


transform

I’d rather send it. Go straight to code

exportdefault new Vuex.Store({ modules: { ... (r => {return r.keys().reduce((c, n) => {                 c[n.match(/(?<=\/).*?(?=\.js)/gi)]=r(n).default                return c            }, [])        })( require.context('./modules/'.true, /\.js$/) )    }})Copy the code

Use an immediately-executed function, passing the require.context() method back

Get the file name map and use reduce to iterate, press the file name as the key, get the module and push the array (do not use push here, use key value, actually can also.) And return

Finally, there is an array with… A can



Here the use of re to remove unnecessary characters, the strange re syntax called forward forward and forward forward forward, related information on their own