vue 微前端实现
vue 微前端实现方案
微前端架构允许将多个独立的前端应用集成到一个主应用中,Vue 可以通过以下几种方式实现微前端:
使用 Module Federation(Webpack 5)
Module Federation 是 Webpack 5 提供的功能,支持跨应用共享模块和动态加载远程模块。
安装依赖:
npm install webpack@5 webpack-cli html-webpack-plugin
配置主应用(host)的 webpack.config.js:
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js'
},
shared: ['vue', 'vue-router']
})
]
};
配置子应用(remote)的 webpack.config.js:
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'remoteApp',
filename: 'remoteEntry.js',
exposes: {
'./RemoteComponent': './src/components/RemoteComponent.vue'
},
shared: ['vue', 'vue-router']
})
]
};
在主应用中动态加载子应用组件:
const RemoteComponent = () => import('remoteApp/RemoteComponent');
使用 single-spa
single-spa 是一个微前端框架,支持 Vue 应用作为子应用。
安装 single-spa:
npm install single-spa single-spa-vue
配置子应用:
import singleSpaVue from 'single-spa-vue';
const vueLifecycles = singleSpaVue({
Vue,
appOptions: {
render() {
return h(App);
},
el: '#vue-app'
}
});
export const bootstrap = vueLifecycles.bootstrap;
export const mount = vueLifecycles.mount;
export const unmount = vueLifecycles.unmount;
在主应用中注册子应用:
import { registerApplication, start } from 'single-spa';
registerApplication({
name: 'vue-app',
app: () => import('vue-app'),
activeWhen: '/vue'
});
start();
使用 iframe
iframe 是最简单的微前端实现方式,但隔离性过强。
主应用中嵌入子应用:
<iframe src="http://localhost:3001" frameborder="0"></iframe>
使用 Qiankun
Qiankun 是基于 single-spa 的微前端解决方案,对 Vue 支持良好。
安装 Qiankun:
npm install qiankun
主应用配置:
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'vue-app',
entry: 'http://localhost:3001',
container: '#vue-container',
activeRule: '/vue'
}
]);
start();
子应用配置:
export async function bootstrap() {
console.log('vue app bootstraped');
}
export async function mount(props) {
new Vue({
render: h => h(App),
}).$mount(props.container ? props.container.querySelector('#app') : '#app');
}
export async function unmount() {
instance.$destroy();
}
样式隔离方案
避免子应用样式污染主应用:
- 使用 CSS Modules 或 Scoped CSS
- 添加命名空间前缀
- 使用 Shadow DOM
通信方案
微前端应用间通信方式:
- 使用 CustomEvent 进行事件通信
- 通过主应用的全局状态管理(如 Vuex)
- 使用 localStorage 或 sessionStorage
每种方案都有其适用场景,Module Federation 适合模块化程度高的项目,single-spa/Qiankun 适合需要独立部署的子应用,iframe 适合需要完全隔离的场景。选择时需考虑团队技术栈、项目规模和性能要求。







