0.0.10 • Published 12 months ago

@gulibs/vite-plugin-react-auto-routes v0.0.10

Weekly downloads
-
License
MIT
Repository
-
Last release
12 months ago

@gulibs/vite-plugin-react-auto-routes

vite插件 React自动路由

NPM

依赖

React Router

安装

npm install --save @gulibs/vite-plugin-react-auto-routes

or

yarn add @gulibs/vite-plugin-react-auto-routes

使用

main.tsx

import '@/index.css'
import { StrictMode, Suspense } from 'react'
import { createRoot } from 'react-dom/client'
import {
  BrowserRouter,
  useRoutes,
} from 'react-router-dom'
import { routes } from '~react-auto-pages'

function App() {
  return (
    <Suspense>
      {useRoutes(routes)}
    </Suspense>
  )
}

const root = createRoot(document.getElementById('root')!)

root.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
)

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import autoRoutePlugin from '@gulibs/vite-plugin-react-auto-routes';

// https://vitejs.dev/config/
export default defineConfig({
  ...
  plugins: [
    react(),
    autoRoutePlugin({
      dirs: [
        { dir: "src/documents", baseRoute: "/documents" }
      ]
    })
  ],
})

vite-env.d.ts

/// <reference types="vite/client" />
/// <reference types="@gulibs/vite-plugin-react-auto-routes/react-routes" />

生成路由

每个目录由需要存在layout.tsxpage.tsxerror.tsx

例如以下文件夹路径

├── documents
│   ├── about
│   │   └── page.tsx
│   ├── error.tsx
│   ├── home
│   │   ├── admin
│   │   │   ├── layout.tsx
│   │   │   ├── login
│   │   │   │   └── page.tsx
│   │   │   └── page.tsx
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── layout.tsx
│   └── page.tsx
├── pages
│   ├── about
│   │   └── page.tsx
│   ├── error.tsx
│   ├── home
│   │   ├── admin
│   │   │   ├── layout.tsx
│   │   │   ├── login
│   │   │   │   └── page.tsx
│   │   │   └── page.tsx
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── layout.tsx
│   └── page.tsx
└── vite-env.d.ts

我们需要设置

autoRoutePlugin({
    dirs: [
        { dir: "src/pages", baseRoute: "/" },
        { dir: "src/documents", baseRoute: "/documents" }
    ]
})

结语

  1. 插件的options是可选的, 如果没设置, 默认会将src/pages目录作为路由生成目录, 如果设置了options, 必须要存在一个根路由即{ dir: "src/{目录名称}", baseRoute: "/" }
  2. dirs属性接收一个目录选项, 被设置的目录会被作为生成路由的目录去解析, dir和baseRoute都必须是唯一的。
0.0.10

12 months ago

0.0.9

12 months ago

0.0.8

12 months ago

0.0.7

12 months ago

0.0.6

12 months ago

0.0.5

12 months ago

0.0.4

12 months ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago