最近在做一个项目是关于微前端 和微服务 今天就说说微前端把,微前端使用的是single-spa
项目是用vue cli3脚手架搭建,single-spa实现了大部分框架(vue、react、angular)的启动和卸载处理的,我这边主应用和微应用都是vue开发的,主应用我后面称为门户,微应用有两个称为子1和子2
npm install single-spa --save -d
npm install single-spa-vue --save -d
准备工作做好后,我们开始分别对门户和子项目进行配置
<script>
// 子项目
export default {
name: "financial",
render(h) {
return h()
}
}
</script>
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')
}]
},]
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].assets;
for (let i = 0; i < assets.length; i++) {
await createScript(publicPath + assets[i]).then(() => {
if (i === assets.length - 1) {
resolve()
}
})
}
});
singleSpa.registerApplication( //注册微前端服务
'auditProject', //子1项目
async () => {
// 注册用函数,
// return 一个singleSpa 模块对象,模块对象来自于要加载的js导出
// 如果这个函数不需要在线引入,只需要本地引入一块加载:
// () => import('xxx/main.js')
// http://127.0.0.1:3001/manifest.json //本地运行 线上打包使用地址直接换成线上地址
let singleVue = null;
await getManifest('http://127.0.0.1:3001/manifest.json', 'app').then(() => {
singleVue = window.singleVue;
});
return singleVue;
},
location => location.pathname.startsWith('/audit') // 配置微前端模块前缀
);
singleSpa.registerApplication(
'singleFinancial', //子2项目
async () => {
let singleVue = null;
await getManifest('http://127.0.0.1:3000/manifest.json', 'app').then(() => {
singleVue = window.singleVue;
});
return singleVue;
},
location => location.pathname.startsWith('/financial')
);
singleSpa.start(); // 启动
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Element from 'element-ui'
import '../src/assets/css/element-variables.scss'
import '../src/assets/css/reset.min.scss'
import '@/assets/iconfont/iconfont.css'
import API from './api/http'
import './single-spa-config.js' //引入single-spa-config.js
Vue.prototype.$API = API
Vue.use(Element)
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
<template>
<el-container class="home">
<el-header style="height: 40px;">
<Header @handle-select="handleSelect" :applications="applications" :userName="userName"></Header>
</el-header>
<el-container>
<el-aside width="160px">
<Menu :routesList="routesList"></Menu>
</el-aside>
<el-main>
<div id="single-vue" class="single-spa-vue">
<div id="audit"></div>
<div id="financial"></div>
</div>
<router-view />
</el-main>
</el-container>
</el-container>
</template>
<script>
import Header from "../components/header";
import Menu from "../components/Sidebar/index";
export default {
name: "Home",
components: {
Header,
Menu,
},
data() {
return {
routesList: [],
applications:[],
userName:''
};
},
methods: {
},
created() {
}
};
</script>
<style lang="scss" scoped>
.home {
width: 100%;
height: 100%;
}
.el-header {
padding: 0;
}
.el-main{
padding: 10px;
}
</style>
门户访问子项目会涉及到跨域
创建http-server.js和webpack.config.js
const express = require('express');
const app = express();
const directory = process.argv[2];
const port = process.argv[3];
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(function(req, res, next) {
next();
});
app.use(express.static(directory));
app.listen(port, () => console.log(`HTTP server listening on port ${
port}, exposing directory ${
directory}.`));
if (process.env.NODE_ENV === 'development') {
module.exports = require('./config/webpack.dev.config');
} else {
module.exports = require('./config/webpack.prod.config');
}
const webpackConfig = require('./webpack.config');
module.exports = {
publicPath: "http://127.0.0.1:3000",
// publicPath: "http://***.**.**.**:3000/financial", //部署地址
assetsDir: 'static',
// css在所有环境下,都不单独打包为文件。这样是为了保证最小引入(只引入js)
css: {
extract: false
},
assetsDir: 'static',
configureWebpack: webpackConfig,
devServer: {
contentBase: './',
compress: true,
}
}
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import '../src/assets/css/reset.min.scss'
import singleSpaVue from "single-spa-vue";
import Element from 'element-ui'
import '../src/assets/css/element-variables.scss'
import API from './api/http'
import {
getDayTime,formateDate,getMonthOneDay} from "@/utils/getNewData"
import * as components from './components'
Vue.prototype.$API = API
Object.keys(components).forEach(key => {
//注册公共组件
const component = components[key]
if (['Col', 'Form', 'Input'].includes(key)) {
Vue.component(`I${
key}`, component)
} else {
Vue.component(key, component)
}
if (['Modal', 'Message', 'Notice'].includes(key)) {
Vue.prototype[`$${
key}`] = component
}
})
Vue.config.productionTip = false
Vue.use(Element)
const vueOptions = {
el: "#financial",
router,
store,
render: h => h(App)
};
// 判断当前页面使用singleSpa应用,不是就渲染
if (!window.singleSpaNavigate) {
delete vueOptions.el;
new Vue(vueOptions).$mount('#app');
}
// singleSpaVue包装一个vue微前端服务对象
const vueLifecycles = singleSpaVue({
Vue,
appOptions: vueOptions
});
export const bootstrap = vueLifecycles.bootstrap; // 启动时
export const mount = vueLifecycles.mount; // 挂载时
export const unmount = vueLifecycles.unmount; // 卸载时
export default vueLifecycles;
<template>
<div class="home">
<el-container>
<el-aside width="120px" v-if="show">
<Menu></Menu>
</el-aside>
<el-main>
<router-view />
</el-main>
</el-container>
</div>
</template>
<script>
import Menu from "../components/Sidebar/index";
import breadcrumb from "../components/breadcrumb";
import {
mapActions } from "vuex";
export default {
name: "Home",
data () {
return {
show:false
}
},
components: {
Menu,
breadcrumb
},
created () {
this.show = !window.singleSpaNavigate //项目单独使用时可以显示自身路由
}
};
</script>
<style lang="scss" scoped>
.home{
height: 100%;
width: 100%;
}
</style>