yang-vite-autoroutes
v1.0.6
Published
A Vite plugin to auto-generate route configurations based on directory structure for Vue Router.
Maintainers
Readme
yang-vite-autoroutes
一个 Vite 插件,用于根据目录结构自动生成 Vue Router 路由配置。
安装
npm install yang-vite-autoroutes使用方法
1. 在 vite.config.js 中配置插件
import { defineConfig } from "vite";
import VitePluginAutoRoutes from "yang-vite-autoroutes";
export default defineConfig({
plugins: [
VitePluginAutoRoutes({
pagesDir: "src/views", // 可选,默认为 'src/views'
routesFile: "src/router/autoRoutes.js", // 可选,默认为 'src/router/autoRoutes.js'
}),
],
});2. 在路由文件中使用生成的路由
// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
import { routes } from "./autoRoutes.js";
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;目录结构示例
src/
views/
Home/
index.vue # 路由: /
About/
index.vue # 路由: /about
index.meta.js # 对应的 meta 文件
User/
_id.vue # 路由: /user/:id
Profile/
index.vue # 路由: /user/profileMeta 文件支持
如果你需要为路由添加额外的配置(如 meta 信息),可以创建对应的 .meta.js 文件:
// src/views/About/index.meta.js
export default {
title: "关于我们",
requiresAuth: true,
meta: {
title: "关于页面",
description: "这是关于我们的页面",
},
};插件会自动检测并加载 .meta.js 文件,将其内容合并到路由配置中。
生成的路由结构
插件会生成类似以下的路由配置:
export const routes = [
{
path: "/about",
component: () => import("src/views/About/index.vue"),
title: "关于我们",
requiresAuth: true,
meta: {
title: "关于页面",
description: "这是关于我们的页面",
},
},
{
path: "/user/:id",
component: () => import("src/views/User/_id.vue"),
},
];注意: 组件使用动态导入(() => import())的方式,这样可以实现代码分割和懒加载。
路由生成规则
- 文件路径转换为路由路径
index.vue文件会被忽略(路径中不包含 "index")- 以下划线开头的文件会转换为动态路由参数(如
_id.vue→:id) - 所有路径都会转换为小写
- 组件使用动态导入,支持代码分割
注意事项
- 确保你的项目支持 ES 模块
- Meta 文件应该使用 ES 模块格式导出(
export default或命名导出) - 插件会在构建时生成路由文件,确保目标目录存在且有写入权限
- 如果 meta 文件加载失败,插件会输出警告信息但不会中断构建过程
- 组件路径使用相对于项目根目录的路径,确保 Vite 能够正确解析
许可证
ISC
