npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tuoyuan/micro-app-vue

v1.0.1

Published

拓源微前端解决方案 - 基于Vue的微前端库

Downloads

10

Readme

@tuoyuan/micro-app-vue

Version License Vue TypeScript

拓源微前端解决方案 - 基于Vue的现代化微前端库

快速开始API文档示例代码在线文档

✨ 特性

  • 🚀 高性能架构 - 支持应用预加载、智能缓存、性能监控
  • 🛡️ 企业级安全 - 完善的错误处理、CSP防护、沙箱隔离
  • 🔧 TypeScript优先 - 完整的类型支持和智能提示
  • 📦 插件化设计 - 可扩展的插件系统,支持自定义功能
  • 🎯 Vue原生集成 - 专为Vue 3设计的组件和API
  • 🔄 强大通信 - 应用间事件通信、全局状态管理
  • 📊 监控分析 - 内置性能监控、错误统计、数据分析
  • 🎨 高度可定制 - 丰富的配置选项和生命周期钩子
  • 🔌 多实例支持 - 支持多租户、多容器场景

📦 安装

# npm
npm install @tuoyuan/micro-app-vue

# yarn
yarn add @tuoyuan/micro-app-vue

# pnpm
pnpm add @tuoyuan/micro-app-vue

🚀 快速开始

底座应用集成

在实际项目中,我们通常组合使用 MicroAppManager 和 Vue 组件来实现完整的微前端集成:

1. 全局管理器配置

import { createMicroAppManager } from '@tuoyuan/micro-app-vue'

// 创建全局管理器实例
const manager = createMicroAppManager({ 
  logLevel: 'INFO',  // 日志级别
  containerId: 'default'  // 容器ID
})

// 初始化管理器
await manager.initialize()

// 添加应用配置到管理器
await manager.addApp({
  appId: 'user-management',
  name: '用户管理',
  url: 'http://localhost:3001',
  routerMode: 'hash',
  accessibleRouter: true,
  preload: true,
  timeout: 10000
})

// 多租户场景
const tenantManager = createMicroAppManager({ 
  logLevel: 'DEBUG',
  containerId: 'tenant-1'
})

2. Vue 应用集成

import { createApp } from 'vue'
import { MicroAppVuePlugin } from '@tuoyuan/micro-app-vue'

const app = createApp(App)

// 使用插件注册组件
app.use(MicroAppVuePlugin)

app.mount('#app')

3. 组件中使用

<template>
  <div>
    <!-- 使用管理器中的配置 -->
    <MicroAppContainer 
      :config="manager.getAppConfig('user-management')"
      :hooks="lifecycleHooks"
      @loaded="onLoaded"
      @error="onError"
      @mounted="onMounted"
    />
    
    <!-- 或者使用本地配置 -->
    <MicroAppContainer 
      :config="localAppConfig"
      @loaded="onLocalAppLoaded"
    />
  </div>
</template>

<script setup>
import { MicroAppContainer } from '@tuoyuan/micro-app-vue'

// 从管理器获取配置
const appConfig = manager.getAppConfig('user-management')

// 本地配置(适用于临时或动态应用)
const localAppConfig = {
  appId: 'temp-app',
  name: '临时应用',
  url: 'http://localhost:3002',
  routerMode: 'hash',
  accessibleRouter: true
}

const lifecycleHooks = {
  beforeLoad: () => console.log('应用开始加载'),
  afterLoad: () => console.log('应用加载完成'),
  beforeMount: () => console.log('应用开始挂载'),
  afterMount: () => console.log('应用挂载完成'),
  onError: (error) => console.error('应用错误:', error)
}

const onLoaded = () => console.log('应用已加载')
const onError = (error) => console.error('加载失败:', error)
const onMounted = () => console.log('应用已挂载')
const onLocalAppLoaded = () => console.log('本地应用已加载')
</script>

4. 组合使用优势

  • MicroAppManager:负责应用生命周期管理、通信、性能监控
  • MicroAppContainer:负责UI展示和用户交互
  • 灵活配置:支持从管理器获取配置或使用本地配置
  • 统一管理:所有应用配置集中管理,便于维护

子应用接入

import { startMicroApp } from '@tuoyuan/micro-app-vue'

// 启动微应用客户端
const microApp = await startMicroApp({
  router: router, // Vue Router实例
  setToken: (token) => {
    localStorage.setItem('token', token)
  },
  debug: true,
  routerMode: 'history',
  accessibleRouter: true,
  routeQueryOptions: {
    // 静态查询参数
    'static-param': 'static-value',
    // 从全局数据获取的查询参数
    'token': {
      type: 'globalData',
      payload: { key: 'token' }
    },
    'user-id': {
      type: 'globalData', 
      payload: { key: 'userId' }
    }
  }
})

// 使用微应用API
if (microApp.isMicroApp) {
  // 监听事件
  microApp.addEventListener('user-login', (data) => {
    console.log('用户登录:', data)
  })

  // 发送事件
  microApp.dispatch('data-updated', { id: 1, name: 'test' })

  // 获取全局数据
  const userData = await microApp.getGlobalData('user')

  // 设置全局数据
  await microApp.setGlobalData('user', { id: 1, name: 'test' })

  // 监听生命周期钩子
  microApp.addHookListener('show', () => {
    console.log('应用显示')
  })

  microApp.addHookListener('hidden', () => {
    console.log('应用隐藏')
  })
}

🔌 插件系统

内置插件

import { 
  LoggingPlugin,
  PerformancePlugin,
  SecurityPlugin,
  AnalyticsPlugin,
  CachePlugin,
  ErrorHandlingPlugin
} from '@tuoyuan/micro-app-vue'

const manager = createMicroAppManager()

// 注册插件
await manager.registerPlugin(new LoggingPlugin({
  level: 'INFO',
  console: true,
  remote: false
}))

await manager.registerPlugin(new PerformancePlugin({
  enabled: true,
  interval: 5000,
  memoryMonitoring: true,
  cpuMonitoring: true
}))

await manager.registerPlugin(new SecurityPlugin({
  enableCSP: true,
  enableSandbox: true,
  enableXSSProtection: true
}))

await manager.registerPlugin(new CachePlugin({
  enabled: true,
  defaultTTL: 300000, // 5分钟
  strategy: 'hybrid'
}))

// 使用高阶函数简化缓存
const cachePlugin = manager.getPlugin('cache')
const getCachedUserData = cachePlugin.createCachedGetter(
  (userId: string) => `user_${userId}`,
  async (userId: string) => {
    const response = await fetch(`/api/users/${userId}`)
    return response.json()
  },
  30 * 60 * 1000 // 30分钟缓存
)

// 自动处理缓存逻辑
const userData = await getCachedUserData('123')

// 支持强制刷新
const freshUserData = await getCachedUserData.forceRefresh('123')

自定义插件

import { BasePlugin } from '@tuoyuan/micro-app-vue'

class CustomPlugin extends BasePlugin {
  id = 'custom-plugin'
  name = 'Custom Plugin'
  version = '1.0.0'
  description = '自定义插件示例'
  author = 'Your Name'

  async install(manager) {
    console.log('插件已安装')
  }

  async beforeAppLoad(config) {
    console.log('应用加载前:', config.appId)
  }

  async afterAppLoad(config) {
    console.log('应用加载后:', config.appId)
  }
}

await manager.registerPlugin(new CustomPlugin())

📚 API文档

MicroAppManager

创建和初始化

import { createMicroAppManager } from '@tuoyuan/micro-app-vue'

// 基本创建
const manager = createMicroAppManager()

// 带配置创建
const manager = createMicroAppManager({
  logLevel: 'INFO',
  containerId: 'default'
})

// 初始化
await manager.initialize()

应用管理

// 添加应用
await manager.addApp({
  appId: 'app-1',
  name: '应用1',
  url: 'http://localhost:3001',
  preload: true
})

// 批量添加应用
await manager.addApps([
  { appId: 'app-1', name: '应用1', url: 'http://localhost:3001' },
  { appId: 'app-2', name: '应用2', url: 'http://localhost:3002' }
])

// 移除应用
await manager.removeApp('app-1')

// 获取应用配置
const config = manager.getAppConfig('app-1')

// 获取所有应用配置
const configs = manager.getAllAppConfigs()

预加载和性能

// 预加载应用
await manager.preloadApp('app-1')

// 检查预加载状态
const isPreloaded = manager.isAppPreloaded('app-1')

// 智能预加载
manager.smartPreload('current-app-id')

// 获取性能指标
const metrics = manager.getAppPerformance('app-1')

// 生成性能报告
const report = manager.generatePerformanceReport()

通信和路由

// 发送消息到应用
await manager.sendMessageToApp('app-1', 'event-type', { data: 'value' })

// 广播消息
manager.broadcastMessage('event-type', { data: 'value' }, {
  from: 'main-app',
  excludeAppIds: ['app-1']
})

// 打开应用路由
await manager.openAppRoute('app-1', {
  route: '/detail',
  params: { id: '123' },
  query: { tab: 'info' }
})

// 打开应用(默认路由)
manager.openApp('app-1')

系统管理

// 获取系统状态
const status = manager.getSystemStatus()

// 设置token获取函数
manager.setGetTokenFunction(() => localStorage.getItem('token'))

// 获取token
const token = manager.getToken()

// 清理资源
await manager.cleanup()

插件管理

// 注册插件
await manager.registerPlugin(plugin)

// 卸载插件
await manager.unregisterPlugin('plugin-id')

// 获取插件
const plugin = manager.getPlugin('plugin-id')

// 获取所有插件
const plugins = manager.getAllPlugins()

// 检查插件是否存在
const hasPlugin = manager.hasPlugin('plugin-id')

工具函数

import {
  generateId,
  isValidUrl,
  validateMicroAppConfig,
  buildRouteUrl,
  deepMerge,
  debounce,
  throttle,
  Logger,
  LogLevel,
  createLogger
} from '@tuoyuan/micro-app-vue'

// 生成唯一ID
const id = generateId()

// 验证URL
const isValid = isValidUrl('http://example.com')

// 验证配置
const errors = validateMicroAppConfig(config)

// 构建路由URL
const url = buildRouteUrl(config, { route: '/detail', params: { id: '123' } })

// 深度合并对象
const merged = deepMerge(target, source)

// 防抖函数
const debouncedFn = debounce(fn, 300)

// 节流函数
const throttledFn = throttle(fn, 300)

// 创建日志记录器
const logger = createLogger({
  moduleName: 'MyModule',
  level: LogLevel.INFO,
  timestamp: true,
  colors: true
})

🎯 配置选项

MicroAppConfig

interface MicroAppConfig {
  /** 应用ID */
  appId: string
  /** 应用名称 */
  name: string
  /** 应用URL */
  url: string
  /** 路由模式 */
  routerMode?: 'hash' | 'history'
  /** 是否可访问路由 */
  accessibleRouter?: boolean
  /** 路由查询参数配置 */
  routeQueryOptions?: Record<string, string | RouteQueryOption>
  /** 预加载配置 */
  preload?: boolean
  /** 超时时间(ms) */
  timeout?: number
}

生命周期钩子

interface LifecycleHooks {
  beforeLoad?: () => void | Promise<void>
  afterLoad?: () => void | Promise<void>
  beforeMount?: () => void | Promise<void>
  afterMount?: () => void | Promise<void>
  beforeUnmount?: () => void | Promise<void>
  afterUnmount?: () => void | Promise<void>
  onError?: (error: Error) => void
}

📖 更多文档

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

MIT License - 详见 LICENSE 文件