Getting to know require.context
require.context is used in webpack to create its own (module) context
webpack will parse require.context() in the code when building
The require.context function receives three parameters:
- directory of folders to search
- whether its subdirectories should also be searched
- and a regular expression that matches files
Example:
let requireServices = require.context(`@/domain`, false, /(\.\/(?:(?!index).)+)\.(ts|js)$/);
(created) a domain folder (not including subdirectories) below, all file names start with .js or . The context of files ending in ts that can be requested by require.
By printing, it can be seen that what is returned is a function, which means that the require.context module exports (returns) a (require) function.
This function has three properties:
- resolve: is a function that returns the module id obtained after the request is resolved
- keys: Also a function that returns an array consisting of all possible requests handled by the context module.
- id: is the module id contained in the context module. It may be used when you use module.hot.accept
Call requireServices .keys() to print out all domain file collections in the ./domain directory
//globalDomainApi.js
let requireServices = require.context(`@/domain`, false, /(\.\/(?:(?!index).)+)\.(ts|js)$/);
let getAllService = function (self, req) {
((requireContext) => {
const arr = requireContext.keys();
(arr || []).forEach((fileName) => {
let config = req(fileName);
let name = fileName.replace(/^\.\//, '').replace(/\.\w+$/, '');
self[name] = config;
});
})(req);
}
export const GlobalDomainApi = function () {
let req = requireServices;
let vm = {
};
getAllService(vm, req);
let servicesStrategy = {
};
for(let key in vm){
servicesStrategy[key] = function (){
return vm[key].default;
}
}
return function (serviceName) {
return servicesStrategy[serviceName]();
}
};
//main.js
import {
GlobalDomainApi} from "./api/globalDomainApi";
Vue.prototype.$domainApi = GlobalDomainApi();
usage:
this.$domainApi("businessPlateApi")
The directory structure is as follows: