Skip to content

Lruler/vite-plugin-react-autoroutes

Repository files navigation

vite-plugin-react-autoroutes

一个仿照umiJs的路由方案

Getting Started

// npm
npm install -D vite-plugin-react-autoroutes

// yarn
yarn install -D vite-plugin-react-autoroutes

// pnpm
pnpm install -D vite-plugin-react-autoroutes

Vite Config

Add to your vite.config.js:

import autoRoute from 'vite-plugin-react-autoroutes';

export default {
  plugins: [
    // ...
    autoRoute({{ pagesDir: 'src/pages/' }}),
  ],
}

Router.tsx

src/router.tsx

import React, { lazy, Suspense, useEffect } from 'react';
import { BrowserRouter as Router, useRoutes, RouteObject } from 'react-router-dom';
import routes, { parse } from 'react-auto-routes';

const syncRouter = (table: SyncRoute.Routes[]): RouteObject[] => {
  let mRouteTable: RouteObject[] = [];
  table.forEach((route) => {
    mRouteTable.push({
      path: route.path,
      element: (
        <Suspense
          fallback={<>Loading</>}
        >
          <route.element />
        </Suspense>
      ),
      children: route.children && syncRouter(route.children),
    });
  });
  return mRouteTable;
};

const Routes = () => {
  return useRoutes(syncRouter(parse(routes, lazy)));
};

const SetRoutes = () => {

  return (
    <Router>
      <Routes />
    </Router>
  );
};

export default SetRoutes

About

A plugin for react set auto routes

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published