微前端架构中React容器无法加载Vue应用:window无render函数
微前端架构中Vue应用无法在React容器中运行?
问题概述
Vue代码无法在容器应用中运行
具体来说,Vue的main.js代码无法运行……
详细说明
我目前正在参考一个项目开发微前端架构(MFA)。架构配置如下:
- 容器应用(React):
容器应用包含头部、底部等公共组件。从远程应用请求asset-manifest.json,加载构建后的JS脚本,然后执行各应用的render函数。
- React应用(远程应用):
微前端应用
- Vue应用(远程应用):
微前端应用
运行流程说明: 每个应用在window对象上声明一个render函数。之后,容器应用从所需应用获取asset-manifest.json,加载构建后的JS文件,执行上述声明的render函数。
问题详情
React应用运行正常,但Vue应用的window对象上未声明render函数。
代码示例
容器应用
import { useEffect } from 'react'; function MicroFrontend({ name, host, history }) { useEffect(() => { const scriptId = `micro-frontend-script-${name}`; const renderMicroFrontend = () => { window[`render${name}`](`${name}-container`, history); }; if (document.getElementById(scriptId)) { renderMicroFrontend(); return; } fetch(`${host}/asset-manifest.json`) .then((res) => res.json()) .then((manifest) => { const script = document.createElement('script'); script.id = scriptId; script.crossOrigin = ''; script.src = `${host}${manifest.files['main.js']}`; script.onload = () => { renderMicroFrontend(); }; document.head.appendChild(script); }); return () => { window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`); }; }); return <main id={`${name}-container`} />; } MicroFrontend.defaultProps = { document, window, }; export default MicroFrontend;
React应用
与Vue项目几乎完全一致。
Vue应用
import Vue from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; Vue.config.productionTip = false; window.renderVueApp = (containerId) => { new Vue({ router, store, render: (h) => h(App), }).$mount(containerId); }; window.unmountVueApp = (containerId) => { const root = document.getElementById(containerId); if (root) { root.remove(); } }; if (!document.getElementById('VueApp-container')) { new Vue({ router, store, render: (h) => h(App), }).$mount('#root'); }
vue.config.js
const WebpackAssetsManifest = require('webpack-assets-manifest'); const { defineConfig } = require('@vue/cli-service'); module.exports = defineConfig({ transpileDependencies: true, configureWebpack: (config) => { config.entry = './src/main.js'; config.plugins = config.plugins.concat( new WebpackAssetsManifest({ output: 'asset-manifest.json', customize(entry) { return { key: `${entry.key.replace('app', 'main')}`, value: `/${entry.value}`, }; }, transform(assets) { return { files: assets, }; }, }), ); }, chainWebpack: (config) => { config.merge({ externals: process.env.NODE_ENV === 'development' ? [] : { vue: 'Vue', 'vue-router': 'VueRouter', }, }); }, });
我实在找不到解决办法,非常苦恼……恳请各位提供帮助。
内容的提问来源于stack exchange,提问作者Taylous
相关产品推荐
相关产品推荐

