The following directories:
Index. Js code:
/** * Dynamically loads the vuex module in modules *@returns* /
function loadModules() {
const modulesFiles = require.context("./modules".true./\.(j|t)s$/i);
const regx = /^\.\/(.*)\.\w+$/;
const modules = modulesFiles.keys().reduce((modules, modulePath) = > {
const moduleName = modulePath.replace(regx, "$1");
const value = modulesFiles(modulePath);
modules[moduleName] = value.default;
return modules;
}, {});
return modules || {};
}
Copy the code
Vue global registry component
Simply import the index.js file in main.js and register vue.use() to invoke all components in the/Components folder on all pages. There is no need to manually import the required components.
index.js
function changStr(str){
return str.charAt(0).toUpperCase()+str.slice(1)}export default {
install(Vue) {
const requireAll=require.context("./components".false./.vue$/)
requireAll.keys().forEach((item) = >{
Vue.component(changStr(item.replace(/ /./,'').replace(/.vue$/,' ')),requireAll(item).default)
})
}
}
Copy the code
Vue routing modularization
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routerList = [];
function importAll(r) {
r.keys().forEach((key) = > {
routerList.push(r(key).default);
});
}
importAll(require.context(".. /routes".true./.routes.js/)); // get a file under routes ending in.routes.js
const routes = [
...routerList,
];
const router = new VueRouter({
routes,
});
export default router;
Copy the code
Batch loading SVG ICONS:
const context = require.context("./svgs".true./\.svg$/)
context.keys().forEach(context) //not used
let modules = context.keys().map(context)
console.log(modules)
Copy the code
The require. The context shows that:
Ps: Common usage scenarios:
-
Icon Icon component loading
-
Load routing modules in batches
-
Global components are loaded in batches
-
Loading of the Store module