从零到一:构建面向AI的Vue微服务架构平台
·

现代前端微服务架构示意图 - Vue 3 + Module Federation 2.0 技术栈
概述
基于 Vue 3 + Module Federation 2.0 的前端微服务架构实践,探索AI原生应用开发新模式
前言
随着前端应用复杂度的不断提升,传统的单体前端架构已经难以满足大型项目的需求。微前端架构应运而生,而 Module Federation 2.0 的出现更是为微前端带来了革命性的变化。
本文将分享我们团队基于 Vue 3 + Module Federation 2.0 构建的微服务架构平台,该平台不仅实现了模块化的微前端架构,还创新性地集成了AI能力,为未来的AI原生应用开发奠定了基础。
架构概览
┌─────────────────────────────────────────────────────────────┐
│ Vue Microservices Platform │
├─────────────────────────────────────────────────────────────┤
│ Shell (Host) │ User Center │ Data Mgmt │ Content │ AI Work │
│ :3000 │ :3001 │ :3002 │ :3003 │ :3004 │
├─────────────────────────────────────────────────────────────┤
│ Shared Lib │ UI Kit │ AI SDK (Plugin System + Gateway) │
└─────────────────────────────────────────────────────────────┘
核心设计理念
- 微服务化:每个业务模块独立开发、独立部署
- AI原生:通过标准化接口让AI感知和操作每个模块
- 共享复用:公共逻辑和UI组件通过packages共享
- 渐进式:支持从单体向微前端平滑迁移
技术栈详解
构建工具链
{
"构建工具": "Vite 5 + pnpm Workspace + Turborepo",
"包管理": "pnpm 9.0.0",
"任务编排": "Turborepo 2.0",
"版本管理": "Changesets"
}
为什么选择这套工具链?
- Vite 5:极速的开发服务器启动和热更新
- pnpm Workspace:高效的包管理和依赖提升
- Turborepo:智能的任务并行和缓存机制
微前端方案
我们选择了 Module Federation 2.0 作为微前端解决方案,相比qiankun等方案有以下优势:
- 原生支持:不需要额外的沙箱机制
- 共享依赖:Vue、Vue Router等可以共享,避免重复加载
- 开发体验:与Vite深度集成,开发时无需构建
- 类型安全:通过TypeScript保证模块间的类型安全
框架选择
// Vue 3.4 + Composition API + <script setup>
<script setup lang="ts">
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
</script>
Module Federation 2.0 实战
Shell应用配置(Host)
// apps/shell/vite.config.ts
import { federation } from '@module-federation/vite'
export default defineConfig({
plugins: [
federation({
name: 'shell',
remotes: {
userCenter: 'userCenter@http://localhost:3001/remoteEntry.js',
dataMgmt: 'dataMgmt@http://localhost:3002/remoteEntry.js',
contentMgmt: 'contentMgmt@http://localhost:3003/remoteEntry.js',
aiWorkbench: 'aiWorkbench@http://localhost:3004/remoteEntry.js'
},
shared: {
vue: { singleton: true, eager: true },
'vue-router': { singleton: true },
pinia: { singleton: true },
'@platform/shared': { singleton: true },
'@platform/ai-sdk': { singleton: true },
'@platform/ui-kit': { singleton: true }
}
})
]
})
Remote应用配置
// apps/user-center/vite.config.ts
export default defineConfig({
plugins: [
federation({
name: 'userCenter',
filename: 'remoteEntry.js',
exposes: {
'./UserRoutes': './src/router/index.ts'
},
shared: {
vue: { singleton: true },
'vue-router': { singleton: true },
pinia: { singleton: true },
'@platform/shared': { singleton: true },
'@platform/ai-sdk': { singleton: true },
'@platform/ui-kit': { singleton: true }
}
})
]
})
动态路由加载
// apps/shell/src/main.ts
async function loadRemoteRoutes() {
const [userRoutes, dataRoutes, contentRoutes, aiRoutes] =
await Promise.allSettled([
import('userCenter/UserRoutes'),
import('dataMgmt/DataRoutes'),
import('contentMgmt/ContentRoutes'),
import('aiWorkbench/AiRoutes')
])
// 动态注入远程路由
for (const { result, parent } of remoteRouteModules) {
if (result.status === 'fulfilled') {
const remoteRoutes = result.value.routes || []
parentRoute.children = remoteRoutes
}
}
}
AI扩展设计
这是本项目最具创新性的部分。我们设计了一套标准化的AI插件系统,让AI能够感知和操作每个微应用。
核心概念
// packages/ai-sdk/src/types.ts
/** AI 插件接口 - 每个微应用通过此接口注册AI能力 */
export interface AIPlugin {
name: string
description: string
tools: AITool[]
contextProvider?: () => PageContext | Promise<PageContext>
}
/** AI 可调用的工具定义 */
export interface AITool {
name: string
description: string
parameters: {
type: 'object'
properties: Record<string, ToolParameter>
required?: string[]
}
execute: (params: Record<string, unknown>) => Promise<unknown>
}
使用示例
// 在数据管理应用中注册AI能力
import { useAIPlugin } from '@platform/ai-sdk'
useAIPlugin({
name: 'dataManagement',
description: '数据管理模块,支持查询和报表生成',
tools: [
{
name: 'queryData',
description: '根据条件查询数据',
parameters: {
type: 'object',
properties: {
table: { type: 'string', description: '数据表名' },
filters: { type: 'object', description: '筛选条件' }
},
required: ['table']
},
execute: async (params) => {
// 执行数据查询
return await fetchData(params.table, params.filters)
}
}
],
contextProvider: () => ({
path: '/data/dashboard',
title: '数据看板',
state: { currentMetrics: ['销售额', '订单量'] },
timestamp: Date.now()
})
})
AI上下文共享
// 全局AI上下文,让AI感知用户当前操作
export interface PageContext {
path: string // 当前路由路径
title: string // 当前页面标题
state: Record<string, unknown> // 页面状态
timestamp: number // 时间戳
}
共享包设计
@platform/shared
提供通用的工具函数和类型定义:
// packages/shared/src/index.ts
export * from './types'
export * from './utils'
export * from './api'
@platform/ui-kit
自研的UI组件库,支持暗色主题:
<!-- packages/ui-kit/src/components/Button.vue -->
<script setup lang="ts">
interface Props {
variant?: 'primary' | 'secondary' | 'danger'
size?: 'sm' | 'md' | 'lg'
}
const props = withDefaults(defineProps<Props>(), {
variant: 'primary',
size: 'md'
})
</script>
<template>
<button :class="['ui-btn', `ui-btn--${variant}`, `ui-btn--${size}`]">
<slot />
</button>
</template>
开发体验
Turborepo 任务编排
// turbo.json
{
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".output/**"]
},
"dev": {
"cache": false,
"persistent": true
},
"lint": {},
"test": {
"dependsOn": ["build"]
}
}
}
开发命令
# 启动所有服务
pnpm dev
# 构建所有应用
pnpm build
# 代码检查
pnpm lint
部署策略
每个微应用独立构建和部署:
# 构建产物目录
apps/shell/dist/
apps/user-center/dist/
apps/data-mgmt/dist/
apps/content-mgmt/dist/
apps/ai-workbench/dist/
通过Nginx反向代理统一入口:
server {
listen 80;
server_name example.com;
# 主应用
location / {
proxy_pass http://localhost:3000;
}
# Remote应用
location /user-center/ {
proxy_pass http://localhost:3001/;
}
location /data-mgmt/ {
proxy_pass http://localhost:3002/;
}
}
总结与展望
通过这套微服务架构平台,我们实现了:
- 模块化开发:每个团队可以独立开发和部署自己的模块
- AI原生集成:为未来的AI应用开发奠定了基础
- 开发效率提升:共享组件和工具库减少重复工作
- 技术栈统一:基于Vue 3 + TypeScript的技术栈保持一致性
未来,我们计划进一步完善:
- AI Agent能力:支持更复杂的AI工作流
- 性能优化:引入更好的代码分割和懒加载策略
- 监控体系:建立完整的前端监控和告警系统
- 多框架支持:通过Module Federation支持React等其他框架
项目地址:Vue Microservices Platform
技术栈:Vue 3.4 + Vite 5 + Module Federation 2.0 + TypeScript + Pinia
欢迎交流讨论!
更多推荐


所有评论(0)