最近在做一个项目是关于微前端 和微服务 今天就说说微前端把,微前端使用的是single-spa
项目是用vue cli3脚手架搭建,single-spa实现了大部分框架(vue、react、angular)的启动和卸载处理的,我这边主应用和微应用都是vue开发的,主应用我后面称为门户,微应用有两个称为子1和子2
安装
1、使用vue cli 快速创建门户和子1、子2
2、门户应用 npm install single-spa --save -d
3、子1和子2分别安装npm install single-spa-vue --save -d
准备工作做好后,我们开始分别对门户和子项目进行配置
主应用门户的配置
1、门户项目内创建两个子项目的页面
<script>
// 子项目
export default {
name: "financial",
render(h) {
return h()
}
}
</script>
2、门户路由里面注册两个子项目的路由
const routes = [{
// 子项目history模式下,父项目的模糊匹配。不建议这样做
// path: '/vue*',
//子1项目
path: '/home',
name: 'Home',
component: Home,
hidden: true,
children: [{
path: '/financial',
name: 'financial',
component: () => import( /* webpackChunkName: "about" */ '../components/Financial')
}]
},
{
//子2项目路径
path: '/home',
name: 'Home',
component: Home,
hidden: true,
children: [{
path: '/audit',
name: 'audit',
component: () => import( /* webpackChunkName: "about" */ '../components/Audit')
}]
},]
3、与main.js同级创建一个single-spa-config.js
import * as singleSpa from 'single-spa'; //引入single-spa
import axios from 'axios';
/*
* createScript:一个promise同步方法。可以代替创建一个script标签,然后加载服务
* */
const createScript = async (url) => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = resolve;
script.onerror = reject;
const firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
});
};
/*
* getManifest:远程加载manifest.json 文件,解析需要加载的js
* */
const getManifest = (url, bundle) => new Promise(async (resolve) => {
const {
data } = await axios.get(url);
const {
entrypoints, publicPath } = data;
const assets = entrypoints[bundle]