Dynamic Routing and Menu Generation System
Table of Contents
- Introduction
- Project Architecture Overview
- Dynamic Routing System
- Menu Generation Mechanism
- Routing Configuration and Mapping
- Performance Optimization Strategies
- Micro-frontend Integration
- Troubleshooting Guide
- Conclusion
Introduction
This system is a modern frontend application built on Vue 3 and TypeScript, adopting dynamic routing and intelligent menu generation mechanisms. Through import.meta.glob for automatic component scanning and lazy loading, combined with script-automated menu configuration generation, a highly extensible micro-frontend architecture is implemented.
Core features of the system include:
- File system-based automatic route discovery
- Intelligent menu generation and configuration management
- Component-level lazy loading optimization
- Micro-frontend architecture support
- Real-time menu update mechanism
Project Architecture Overview
Diagram sources
Dynamic Routing System
Route Automatic Discovery Mechanism
The system implements automatic component scanning and route registration through import.meta.glob:
const widgetsMap: any = import.meta.glob('./widgets/*/*.vue', {
eager: true,
import: 'default',
})
const widgetsTsxMap: any = import.meta.glob('./widgets/*/Views/*.tsx', {
eager: true,
import: 'default',
})
Advantages of this mechanism:
- Zero-configuration Routing: No need to manually maintain route tables
- Automatic Discovery: New components automatically join the routing system
- Type Safety: TypeScript provides complete type inference
- Performance Optimization: Supports on-demand loading and code splitting
Route Parsing Flow
Diagram sources
Route Configuration Structure
Each route contains the following core fields:
interface RouteConfig {
path: string // Route path
name: string // Menu name
component: any // Component instance
icon: string // Icon identifier
meta: { // Metadata
widgetName: string // Component name
}
}
Section sources
Menu Generation Mechanism
Automatic Menu Generation Flow
The menu generator automatically creates menu configuration by parsing the index.ts file of components:
// Parse AST to get canvasView configuration
const ast = parser.parse(file, {
sourceType: 'module',
plugins: ['typescript'],
})
// Extract menu configuration information
properties.forEach((prop) => {
if (prop.key.name === 'canvasView') {
// Process canvasView configuration
}
if (prop.key.name === 'name') {
row.name = prop.value.value
}
if (prop.key.name === 'icon') {
row.icon = prop.value.name
}
})
Menu Configuration Structure
Diagram sources
Menu Field Details
| Field Name | Type | Purpose | Example |
|---|---|---|---|
name | string | Menu display name | "Traceability Report" |
icon | string | Icon identifier | "t1" |
patchName | string | Component unique identifier | "TraceManagement" |
path | string | Route path | "/information-base/TraceManagement" |
notPage | boolean | Whether it's a page component | false |
Section sources
Routing Configuration and Mapping
File System Mapping Relationship
The system implements automatic mapping of routes and menus through strict file structure conventions:
src/widgets/
├── TraceManagement/
│ ├── index.ts # Menu configuration entry
│ ├── Views/
│ │ └── TraceManagement.tsx
│ └── Settings/
│ └── TraceManagement.settings.tsx
├── SystemManagement/
│ ├── index.ts
│ ├── Views/
│ │ └── SystemManagement.vue
│ └── ...
└── ...
Route Matching Rules
Diagram sources
Nested Route Configuration
The system supports complex nested route structures, implemented through the provider function for component wrapping:
export function provider(
Widget: Component,
data: boolean | Component = false,
isFullyCover: boolean = false,
defaultConfig: Record<string, any> = {}
) {
return (arg: any) => {
return h(Provider, {
widgetProps: arg,
widgetName: Widget.name,
isFullyCover,
isWidget,
defaultConfig,
NestedComponents,
}, {
default: h(Widget, props)
})
}
}
Section sources
Performance Optimization Strategies
Preloading Strategy
The system employs multiple strategies to optimize route loading performance:
- Eager Loading: Preload critical components during build
- Lazy Loading: Load non-critical components on demand
- Caching Mechanism: Use browser cache to reduce repeated loading
// Eager loading configuration
const widgetsMap: any = import.meta.glob('./widgets/*/*.vue', {
eager: true,
import: 'default',
})
// Lazy loading configuration
const lazyComponent = () => import('./LazyComponent.vue')
Memory Optimization
Caching Mechanism
The system implements multi-level caching mechanisms:
- Component Cache: Loaded components remain in memory
- Route Cache: Route configuration cached in global state
- Menu Cache: Menu structure cached in localStorage
Section sources
Micro-frontend Integration
Plugin-based Architecture
The system supports micro-frontend architecture through a plugin mechanism:
export default function VitePluginWidgetProvider(): any {
return {
name: 'vite-plugin-widget-provider',
apply: 'build',
transform(code, id) {
if (fileRegex.test(id)) {
if (regex.test(id)) {
const codeData = parseCode(code)
const transformCode = mergeCodeString(codeData, code)
return { code: transformCode, map: null }
}
}
},
}
}
Component Isolation
Diagram sources
Runtime Integration
The system supports runtime dynamic loading of micro-frontend components:
// Dynamically import components
const getWidgetSettingsFile = async (widgetName: string) => {
const widgetPath = `./widgets/${widgetName}/Settings/${widgetName}.settings`
const fn = async (suffix: string) => {
const WidgetSettings = await import(/* @vite-ignore */ widgetPath + suffix)
currentWidgetSettings.value = markRaw(WidgetSettings.default)
return currentWidgetSettings.value
}
try {
await fn('.tsx')
} catch (error) {
await fn('.vue')
}
}
Section sources
Troubleshooting Guide
Common Issues and Solutions
1. Route Cannot Load
Symptoms: 404 error when accessing route Cause: Incorrect component file path or index.ts configuration error Solution:
# Check component file structure
ls -la src/widgets/YourWidget/
# Verify index.ts export
cat src/widgets/YourWidget/index.ts
2. Menu Not Displaying
Symptoms: Component exists but menu doesn't display Cause: canvasView configuration missing or notPage set to true Solution:
// Ensure index.ts contains correct canvasView configuration
export default {
canvasView: provider(YourComponent),
name: "Display Name",
icon: "Icon Name"
}
3. Build Failure
Symptoms: Error during npm run build Cause: TypeScript type checking failure or plugin configuration error Solution:
# Clear cache and rebuild
rm -rf node_modules/.cache
npm run build
Debugging Tools
The system provides rich debugging functionality:
// Enable debug mode
const onOpenDebugger = async () => {
await settingDebuggerMode()
ElMessage.success('Debug mode enabled successfully')
}
// Route state monitoring
watch(() => route?.meta, (meta) => {
console.log('Route change:', meta)
})
Section sources
Conclusion
This dynamic routing and menu generation system implements a highly automated and extensible frontend architecture through innovative technical solutions:
Core Advantages
- High Automation: Fully automated from component discovery to menu generation
- Excellent Performance: Multi-level caching and lazy loading strategies ensure optimal performance
- Strong Extensibility: Supports micro-frontend architecture and plugin-based extensions
- Developer Friendly: Zero-configuration development experience reduces maintenance costs
Technical Highlights
- Intelligent Route Discovery: Automatic route generation based on file system
- Real-time Menu Updates: Runtime dynamic menu structure updates
- Type Safety Guarantee: Complete TypeScript type support
- Micro-frontend Integration: Native support for micro-frontend architecture
Best Practice Recommendations
- Follow Naming Conventions: Strictly follow component naming and file structure conventions
- Reasonable Cache Usage: Adjust caching strategy according to business requirements
- Performance Monitoring: Regularly monitor memory usage and loading performance
- Version Management: Establish comprehensive component version management and release process
This system provides a powerful and flexible infrastructure for enterprise-level frontend applications, meeting complex business scenario requirements while maintaining good development experience and operational efficiency.