Skip to content

weiquanju/vite-vue-route-generator

Repository files navigation

vite-vue-route-generator

Automate the tedious task of creating Vue Router configurations. Simply define your page components, and let this plugin handle the rest.

If you think this project is helpful to you, please light up the stars⭐️ for us.

Dependent
  • Vite@2.9.0

  • Vue@3.0.0

  • Vue-Router@4.0.0


Features

  • 🚀 Automatically generate Vue Router configurations based on the directory structure of your page components.

  • 🦾 Automatically generate the name of the route based on the file name. This helps with better support for keep-alive.

  • 📥 Support Vue and Vue TSX/JSX file formats.

  • 💡 Support dynamic route matching with params.

中文文档

Getting Started

Install vite-vue-route-generator

# Choose a package manager you like.
npm install vite-vue-route-generator --save
# or
yarn add vite-vue-route-generator
# or
pnpm install vite-vue-route-generator

Usage

Example of src/views/:
├─index.vue
└─foo
    ├─ app.tsx
	└─ index.vue
Generate route
// file: src/router/index.ts
import { createRouter, createWebHistory } from "vue-router";
import { getRoutes } from "vite-vue-route-generator";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // 👇 Use globe syntax to retrieve all files in the page view directory
  routes: getRoutes(import.meta.glob("../views/**/**.vue"), {
    /** 
     * Required. The root path of the directory tree, using relative paths, ending with '/'
     */
    pathRoot: "../views/",
    debugger: true,// To print the route.
  }),
});

export default router;
Result
// Based on the routing configuration generated from the directory above:
[
	{
		"path": "/foo",
		"children": [
			{
				"name": "FooApp",
				"path": "app",
				"component": ()=>import('../views/foo/app.tsx')
			},
			{
				"name": "FooIndex",
				"path": "",
				"component": ()=>import('../views/foo/index.vue')
			}
		]
	},
	{
		"name": "Index",
		"path": "/",
		"component": ()=>import('../views/index.vue')
	}
]


Naming rules
  • Homepage filename is HomeView.vue or Index.uve, index.vue (Must)

  • NotFound page is 404.vue or notfound.vue, NotFound.vue (Must)

Support file formats

  • .vue

  • .tsx

  • .jsx

Dynamic Route Matching with Params
  • Parameter

src/views/User/list-[pid]-[userName].vue (File)

/User/list-:pid-:userName (Vue route configure parameter of path)

/User/list-456-Foo (Browser access path)

Route Params in Vue SFC

<template>
{{$route.params.pid}}
<!-- print 123 -->
{{$route.params.userName}}
<!-- print Foo -->
</template>

Contribution

Welcome to contribute code.

pnpm install
pnpm run build
# or
npm i
npm run build

License

MIT Copyright (c) 2022-PRESENT weiquanju

About

Automatically generate Vue routing configuration based on file path.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published