There are N routing files in the SRC/Router/Component folder of the project

Path: SRC/router/component/about. Jsimport Layout from "@/layout";
export default [  // Export with export default
  {
    path: "/about".component: Layout, } ..... ] Path: the SRC/router/component/news. Jsimport Layout from "@/layout";
export default [  // Export with export default
  {
    path: "/news".component: Layout,
   }
   .....
] 

Copy the code

Router /index.js Route import JS file, one by one how to do?

Like this!

You can userequire.contextOptimize project code

We encapsulate a method that automatically imports routes

Path: the SRC/utils/importAll. Js// In a simple way
export function importAllFn(ctx = {}) {
  let routers = [];
  ctx.keys().forEach(function (item) {
    routers.push(ctx(item).default);
  });
  routers = routers.filter((re) = >!!!!! re).flat(2);  // Make sure the incoming route cannot be empty // There is a two-dimensional array to be flattened
  return routers;
}

/ / after optimization
export function importAllFn(ctx = {}) {
  let routers = [];
  routers = (ctx.keys().map((item) = > ctx(item).default || [])).flat(2)  // routers = routers.flat(2); 
  return routers;
}

// Continue to optimize
export function importAllFn(ctx = {}) {
  return (ctx.keys().map((item) = > ctx(item).default || [])).flat(2)}Copy the code

Import to router/index.js

Path: the SRC/router/index. Js// Automatically import routing methods
import { importAllFn } from "@/utils/importAll";

ImportAll is equivalent to routes
let importAll = importAllFn(require.context("./component".false./.js$/));
Copy the code

A project can compress dozens of lines of code into one. If there is a new route in the future, you only need to create js files in the router/ Component folder. You do not need to manually import the route again. The encapsulation method will automatically import the route, which is convenient….