插件配置
vitarx-router 内置了 Vite 文件路由插件,通过扫描页面目录自动生成路由配置,无需手动维护路由表。
配置 Vite 插件
在 vite.config.ts 中引入并配置插件:
ts
// vite.config.ts
import vitarx from '@vitarx/plugin-vite'
import VitarxRouter from 'vitarx-router/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
vitarx(),
VitarxRouter({
pages: 'src/pages',
pathStrategy: 'kebab',
dts: true
})
]
})FileRouterOptions 配置项
完整配置项参见 FileRouterOptions API
pages 配置
pages 支持字符串或配置对象,也支持数组形式指定多个页面目录:
ts
// 字符串形式
VitarxRouter({ pages: 'src/pages' })
// 配置对象形式
VitarxRouter({
pages: {
dir: 'src/pages',
include: ['**/*.{jsx,tsx}'],
exclude: ['**/node_modules/**', '**/dist/**'],
prefix: '',
group: false
}
})
// 数组形式 — 多个页面目录
VitarxRouter({
pages: ['src/pages', { dir: 'src/admin', prefix: '/admin', group: true }]
})importMode 配置
importMode 控制组件的导入方式,支持 'lazy'(默认)、'sync' 和自定义函数。详见 路由懒加载 - 文件路由的导入模式。
dts 配置
dts 控制类型声明文件的生成,支持 false(默认)、true 或自定义文件名。详见 TypeScript 支持 - 路由类型声明。
extendRoute 配置
extendRoute 允许你在路由生成后对其进行修改:
ts
VitarxRouter({
extendRoute(route) {
// 为所有路由添加认证标记
route.meta ??= {}
route.meta.auth = true
}
})transform 配置
transform 用于对文件内容进行预处理,常用于支持 Markdown 文件作为页面:
ts
import path from 'node:path'
VitarxRouter({
transform(content, file) {
const { ext, name } = path.parse(file)
if (ext === '.md') {
const html = markdownToHtml(content)
return `export default function #123;name}() { return #123;html} }`
}
return content
}
})使用生成的路由
插件会在构建时生成虚拟模块 virtual:vitarx-router:routes,你可以通过 vitarx-router/auto-routes 导入:
ts
// src/router/index.ts
import { createRouter } from 'vitarx-router'
import { routes, handleHotUpdate } from 'vitarx-router/auto-routes'
export const router = createRouter({
routes
})
// 开发环境热更新
if (import.meta.hot) {
handleHotUpdate(router)
}引用:关于
handleHotUpdate的详细用法,请参阅 热更新。
完整示例
ts
// vite.config.ts
import vitarx from '@vitarx/plugin-vite'
import VitarxRouter from 'vitarx-router/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
vitarx(),
VitarxRouter({
pages: 'src/pages',
pathStrategy: 'kebab',
importMode: 'lazy',
dts: 'typed-router.d.ts',
extendRoute(route) {
route.meta ??= {}
route.meta.layout ??= 'default'
}
})
]
})ts
// src/router/index.ts
import { createRouter } from 'vitarx-router'
import { routes, handleHotUpdate } from 'vitarx-router/auto-routes'
export const router = createRouter({
routes
})
if (import.meta.hot) {
handleHotUpdate(router)
}