react自动化配置路由表的实现

  1. 创建一个这种目录按功能模块分页面


    image.png
  2. 每个目录均已这种形式存放文件,其中route就是本功能模块的路由列表


    image.png
export default [
  /*
   *path: 定义路由的路径
   *component: 需要展示页面路径
   *name: 本个路由的名字
   *lazy: 这个路由是否懒加载
  */
  { path: "/", component: '/home', name: "首页", lazy: true, auth: true }
];
  1. 在view下的index.js集成路由表

    主要通过require进行来读取文件里面的内容,来进行自动化导入以及配置路由表
import React, {lazy, Suspense} from 'react';
// 这里定义的是每个功能模块的文件夹名
export const ModularList = [
    'home',
    'blog',
    'poetry',
    'photos'
]

let _apiObj = {}
let _routerObj = []

ModularList.map(modularName => {
    // 集成api请求
    try {
        const importInfo = require(`./${modularName}/api/index`)
        const ModularInfo = importInfo.ModularInfo || {}
        const ActionList = importInfo.default || {}
        _apiObj[modularName] = {
            ModularInfo,
            ActionList
        }
    } catch (e) {}

    // 集成路由
    try {
        const importInfo = require(`./${modularName}/route/index`)
        const route = importInfo.default
        route.forEach(el => {
            const component = el.lazy ? lazy(() => import(`../views/${modularName}/page${el.component || el.path}/index`)) : require(`../views/${modularName}/page${el.component || el.path}/index`).default
            _routerObj.push({
                ...el,
                component
            })
        })
    } catch (e) {}
})
export const apiObj = _apiObj
export const routerObj = _routerObj
export const menuObj = _routerObj.filter(el => el.menu)
  1. 直接使用
import {routerObj} from '../views/index'
console.log(routerObj)

会得到


image.png

和上次的react实现路由守卫就可以配合用了

你可能感兴趣的:(react自动化配置路由表的实现)