vite-plugin-generoutes
v0.2.10
Published
A Vite plugin that generate routes based on the file structure, supports dynamic routes, and supports custom meta data for each route.
Downloads
111
Readme
vite-plugin-generoutes
A Vite plugin that generate routes based on the file structure, supports dynamic routes, and supports custom meta data for each route.
Usage
- Install the plugin:
npm install vite-plugin-generoutes
- Add the plugin to your
vite.config.js
:
import { defineConfig } from 'vite'
import generoutes from 'vite-plugin-generoutes'
export default defineConfig({
plugins: [
generoutes()
// ... other plugins
]
})
- Create your page files(
index.vue
or[...all].vue
) in thesrc/pages
directory. Each file in this directory will be treated as a route.
src/routes/pages
├── index.vue
├── [...all].vue
├── user/
│ ├── index.vue
│ ├── [id]
│ │ └── index.vue
└── post
├── index.vue
└── [...all].vue
The above example will generate the routes file src/pages/generoutes.js
with the following content:
export const routes = [
{
name: 'Index',
path: '/',
component: () => import('/src/pages/index.vue'),
meta: {},
},
{
name: 'User',
path: '/user',
component: () => import('/src/pages/user/index.vue'),
meta: {},
},
{
name: 'User_[id]',
path: '/user/:id',
component: () => import('/src/pages/user/[id]/index.vue'),
meta: {},
},
{
name: 'User_Post',
path: '/user/post',
component: () => import('/src/pages/user/post/index.vue'),
meta: {},
},
{
name: 'Index_[...all]',
path: '/:pathMatch(.*)*',
component: () => import('/src/pages/[...all].vue'),
meta: {},
},
{
name: 'User_Post_[...all]',
path: '/user/post/:pathMatch(.*)*',
component: () => import('/src/pages/user/post/[...all].vue'),
meta: {},
},
]
- Import the generated routes and create a router instance:
import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from './pages/generoutes'
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
Features
- Generate routes based on the file structure.
- Support dynamic routes.
- Support multiple NotFound routes.
- Support custom meta data for each route.
- Support ghost paths, For example, the (admin) folder will not be part of the route path, which is very useful for folder grouping.
- Support immediate update of the routes file when the file structure or defineOptions changes.
- Support nested route.
Custom route info,including name and meta
You can define name
and meta
fields in the defineOptions
of your .vue
file, which will be used to override the default properties of the generated route. The name
field will be used as the route name, which is very useful for KeepAlive
. Any property in defineOptions.meta
will be used as a property of the route meta
, which makes the route metadata very flexible.
When you make any changes that may affect the route result, the src/pages/generoutes.js
file will be updated immediately, and the page will be refreshed without restarting the server.