likes
comments
collection
share

约定式路由生成神器:vite-plugin-pages

作者站长头像
站长
· 阅读数 8

前言

文章主要写了关于在 Vite 中使用 glob 根据文件系统自动生成路由,但看到有伙伴介绍这个目前有现成的 vite 插件:vite-plugin-pages

我一时就来了兴趣,搭建了个 vite 工程了解了下,真的可以,而且配置很简单,下面我来介绍一下这个插件的使用

安装插件

  1. 使用命令搭建一个 vue3 工程:
pnpm create vite vue3-demo -- --template vue-ts
  1. 安装 vue-routervite-plugin-pages
pnpm add vue-router

pnpm add vite-plugin-pages -D

配置插件

  1. 打开 vite.config.ts 文件,新增配置:
 import { defineConfig } from 'vite'
 import vue from '@vitejs/plugin-vue'
 import pages from 'vite-plugin-pages'

 // https://vitejs.dev/config/
 export default defineConfig({
   plugins: [
     vue(),
     pages({
       dirs: "src/views", // 需要生成路由的文件目录,默认就是识别src下面的pages文件
       exclude: ["**/components/*.vue"], // 排除在外的目录,上面配置目录的例子,里面有 components 目录,我们不希望他被解析为路由
       extendRoute(route, parent) {
         if (route.path === '/') {
           //给默认路由加一个redirect,默认为index.vue
           return {
             ...route,
             redirect: '/about'
           }
         }
       }
     }),
   ]
 })
  1. 配置 router/index.ts 路由文件:
import {
  createRouter,
  createWebHistory
} from "vue-router";
import routes from "~pages";
const router = createRouter({
  history: createWebHistory(),
  routes,
});
export default router;
  1. main.ts 中挂载路由:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')

文件系统即是路由

  1. 我们简单创建几个菜单文件: 约定式路由生成神器:vite-plugin-pages
  2. 我们在 router/index.ts 打印一下 routes ,会得到默认的路由配置,这时候我们就可以访问路由了: 约定式路由生成神器:vite-plugin-pages
  3. 如果我们想覆盖 route 配置,可以在文件中添加 <route> 路由信息:
<route>
 {
   name:'new-about',
   meta: {
     requiresAuth: false,
     layout:'top'
   }
 }
</route>

<route> 里面的配置会直接覆盖默认配置,你也可以使用 yaml 格式:

<route lang="yaml">
name: new-about
meta:
  requiresAuth: true
  layout: top
</route>
  1. 配置动态路由,只需要用 [] 符号包裹:
src/pages/users/[id].vue -> /users/:id (/users/one)
src/pages/[user]/settings.vue -> /:user/settings (/one/settings)
  1. 配置 404 拦截页面,在 src/views 目录下添加 [...all].vue约定式路由生成神器:vite-plugin-pages

路由生成规则

src/views/index.vue -> /
src/views/index/a.vue -> /a // 这里的a.vue就是index.vue的子路由(children)
src/views/father/index.vue -> /father
src/views/father.vue -> /father
src/views/father/son.vue -> /father/son
src/views/father/[id].vue -> /father/:id
src/views/[father]/son.vue -> /:father/son
src/views/[…all].vue ->文件用来适配404页面

更多配置请参考:vite-plugin-pages

总结

个人感觉这个插件功能还是挺实用的,可以用在我们的项目上,就不用每次都要手写路由配置了,也更加容易维护。

不得不感叹现在前端开发的工具真的是越来越多了,也越来越实用,vite 还有很多实用的功能待我们去探索,这里给作者和 尤雨溪 老板一个赞👍🏻🫰

转载自:https://juejin.cn/post/7347251816617705522
评论
请登录