Usage scenarios

In the current front-end development process, most of the single-page modular development, so when the module reaches a certain size, it is a little cumbersome to manually add the export reference, so we can use webpack require.context to achieve our dynamic import, just need to write the code according to the specified format

Parameters that

Require. context takes three arguments:

1 directory {String} - Read the path of the file. 2 useSubdirectories {Boolean} - Whether to traverse the subdirectories of the file. 3 regExp {regExp} - Match the re of the fileCopy the code

Here’s an example:

const files = require.context("./modules", false, /\.js$/)
Copy the code

Modules: this line of code reads modules and js files

Return instructions

Require. context returns a function that looks like this:

1 resolve {Function} – Takes request, which is the relative path of the matched file under the test folder, and returns the relative path of the matched file relative to the entire project

2 keys {Function} – Returns an array of the names of successfully matched modules

3 id {String} – The id of the execution environment, which returns a String, mainly used in module.hot.accept.

All three of these are properties of functions.

Here’s an example:

const files = require.context("./modules", false, /\.js$/);
let modules = {
    state: {},
    mutations: {},
  actions: {},
  getters: {}
};

files.keys().forEach((key) => {
  Object.assign(modules.state, files(key)["state"]);
  Object.assign(modules.mutations, files(key)["mutations"]);
  Object.assign(modules.actions, files(key)["actions"]);
  Object.assign(modules.getters, files(key)["getters"]);
});
const store = new Vuex.Store(modules);
export default store;
Copy the code

This code does several things:

1 use require.context to get all js files under Modules (without traversing subdirectories). 2 Perform traversal of the resulting files to get the corresponding exported data of each fileCopy the code

This method directly assembles the contents of each file into a new store data structure;

conclusion

Through the above parameters and examples, for our modular development is a certain help. There is no need to manually import too many modules. Of course there are a lot of places to use it in the project;

1 VuEX status Management

2 Route Registration

3. Elegant use of SVG, with require.context, almost every project has its own iconfont library, just need to constantly add icon to it