阿里云主机折上折
  • 微信号
Current Site:Index > Micro-frontend architecture support solutions

Micro-frontend architecture support solutions

Author:Chuan Chen 阅读数:29173人阅读 分类: 构建工具

Micro-Frontend Architecture Support Solutions

The core of micro-frontend architecture lies in breaking down large frontend applications into independently developed, deployed, and run sub-applications. Vite.js, as a modern frontend build tool, offers various possibilities for implementing micro-frontends with its native ESM support and fast development experience.

Module Federation-Based Solution

Vite supports Module Federation through plugins, a key technology for sharing resources in micro-frontends. Here’s a typical configuration example:

// vite.config.js
import { defineConfig } from 'vite'
import federation from '@originjs/vite-plugin-federation'

export default defineConfig({
  plugins: [
    federation({
      name: 'host-app',
      remotes: {
        remoteApp: 'http://localhost:5001/assets/remoteEntry.js'
      },
      shared: ['react', 'react-dom']
    })
  ]
})

Features of this solution include:

  • Dynamic runtime loading of remote modules
  • Shared dependencies to avoid duplicate bundling
  • Independent development and deployment capabilities
  • Support for version isolation

iframe Integration Solution

The traditional yet stable iframe approach is also applicable in Vite:

<iframe 
  src="http://child-app.com"
  style="width:100%; height:500px; border:none;"
  sandbox="allow-same-origin allow-scripts"
></iframe>

Key considerations:

  • Use the sandbox attribute to control security policies
  • Implement parent-child communication via postMessage
  • Natural style isolation
  • Performance overhead must be considered

Custom Elements Solution

Web Components integrate seamlessly with Vite:

// child-app/main.js
import { defineCustomElement } from 'vue'
import App from './App.ce.vue'

customElements.define('child-app', defineCustomElement(App))

The host application simply uses:

<child-app></child-app>

Key advantages:

  • Truly technology-agnostic
  • Shadow DOM provides style isolation
  • Standardized browser support
  • Simplified lifecycle management

Build-Time Composition Solution

Vite supports compile-time composition via build plugins:

// vite.config.js
import { defineConfig } from 'vite'
import childApp from 'vite-plugin-child-app'

export default defineConfig({
  plugins: [
    childApp({
      entry: 'path/to/child-app',
      prefix: 'child-'
    })
  ]
})

Features of this solution:

  • Dependencies determined at compile time
  • Generates a single deployment bundle
  • Greater potential for build optimizations
  • Relatively lower flexibility

Route-Level Integration Solution

Example of route-based micro-frontend integration:

// host-app/src/micro-fe.js
const apps = {
  'app1': { 
    entry: 'http://localhost:5001',
    container: '#micro-container'
  },
  'app2': {
    entry: 'http://localhost:5002',
    container: '#micro-container'
  }
}

export function loadApp(name) {
  const app = apps[name]
  return import(/* @vite-ignore */ app.entry)
    .then(module => module.mount(app.container))
}

Example route configuration:

import { loadApp } from './micro-fe'

const routes = [
  {
    path: '/app1/*',
    component: () => loadApp('app1')
  },
  {
    path: '/app2/*',
    component: () => loadApp('app2')
  }
]

Style Isolation Solutions

Several ways to implement style isolation in Vite:

  1. CSS Modules
// child-app/App.vue
<style module>
.container {
  /* Styles automatically scoped */
}
</style>
  1. Scoped CSS
<style scoped>
/* Automatically adds attribute selectors */
</style>
  1. Manual Prefixing
// vite.config.js
export default defineConfig({
  css: {
    modules: {
      generateScopedName: 'child-[name]__[local]'
    }
  }
})

State Management Solutions

Patterns for cross-application state sharing:

  1. Custom Event Bus
// shared/event-bus.js
import emitter from 'tiny-emitter'
export default new emitter()
  1. Shared State Library
// shared/store.js
import { reactive } from 'vue'
export const store = reactive({
  user: null,
  theme: 'light'
})
  1. URL State Synchronization
// Watch for route changes
watch(route, (newRoute) => {
  if (newRoute.query.theme) {
    store.theme = newRoute.query.theme
  }
})

Performance Optimization Strategies

Vite-specific micro-frontend optimization techniques:

  1. Dependency Pre-Bundling Configuration
// vite.config.js
optimizeDeps: {
  include: ['shared-vue', 'shared-utils']
}
  1. Dynamic Import Optimization
const app = await import(/* webpackPreload: true */ `./apps/${name}.js`)
  1. Build Output Analysis
vite build --report

Debugging and Error Handling

Micro-frontend-specific debugging tips:

  1. Sourcemap Configuration
// vite.config.js
build: {
  sourcemap: 'hidden'
}
  1. Error Boundary Components
<template>
  <ErrorBoundary>
    <MicroApp />
  </ErrorBoundary>
</template>

<script>
export default {
  errorCaptured(err) {
    logErrorToService(err)
  }
}
</script>
  1. Cross-Application Log Aggregation
window.addEventListener('error', (event) => {
  if (event.filename.includes('child-app')) {
    sendToMonitoring(event)
  }
})

Deployment Strategies

Deployment solutions for different environments:

  1. Independent Deployment
# Child application
vite build --base=/child-app/

# Host application
vite build --base=/
  1. Combined Deployment
location /child-app/ {
  alias /path/to/child-app/dist/;
  try_files $uri $uri/ /child-app/index.html;
}
  1. CDN Deployment
// Dynamically set publicPath
__webpack_public_path__ = window.childAppCdnUrl

Testing Strategies

Micro-frontend-specific testing considerations:

  1. Integration Test Configuration
// playwright.config.js
projects: [
  {
    name: 'host-app',
    testMatch: '**/host/**'
  },
  {
    name: 'child-app',
    testMatch: '**/child/**'
  }
]
  1. Contract Testing
// shared-api.spec.js
test('Shared API Contract', () => {
  expect(window.microFE).toHaveProperty('registerApp')
})
  1. Visual Regression Testing
// image.spec.js
expect(await page.screenshot()).toMatchSnapshot()

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.