Automatically load modules in vue

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:

  1. directory of folders to search
  2. whether its subdirectories should also be searched
  3. 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:

  1. resolve: is a function that returns the module id obtained after the request is resolved
  2. keys: Also a function that returns an array consisting of all possible requests handled by the context module.
  3. 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:
insert image description here

Guess you like

Origin blog.csdn.net/baidu_39009276/article/details/128022911