什么是微前端
微前端指的是在于瀏覽器中得微服務(wù)。
微前端是用戶(hù)界面中的一部分,可以分割為多個(gè)react珍昨、Vue、Angular等框架來(lái)渲染組合句喷。沒(méi)有微前端可由不同的開(kāi)發(fā)團(tuán)隊(duì)只管里選擇不同框架镣典。比如擁有獨(dú)立的git倉(cāng)庫(kù)、獨(dú)立構(gòu)建等唾琼。
構(gòu)建主應(yīng)用
1兄春、安裝single-spa依賴(lài)npm install single-spa --save -d并在mian.js中引入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './single-spa-config.js'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
2、創(chuàng)建single-spa的配置文件為single-spa-config
singleSpa.registerApplication: 注冊(cè)子應(yīng)用;
appName: 子應(yīng)用名稱(chēng);
applicationOrLoadingFn: 子應(yīng)用注冊(cè)函數(shù)锡溯,子應(yīng)用需要返回 single-spa 的生命周期對(duì)象;
activityFn: 回調(diào)函數(shù)入?yún)?location 對(duì)象卦尊,可以寫(xiě)自定義匹配路由加載規(guī)則;
/* eslint-disable */
import * as singleSpa from 'single-spa'; //導(dǎo)入single-spa
import axios from 'axios';
/*
* runScript:一個(gè)promise同步方法十拣∥酝粒可以代替創(chuàng)建一個(gè)script標(biāo)簽盹舞,然后加載服務(wù)
* */
const runScript = 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:遠(yuǎn)程加載manifest.json 文件,解析需要加載的js
* */
const getManifest = (url, bundle) => new Promise(async (resolve) => {
console.log(url, bundle)
const { data } = await axios.get(url);
const { entrypoints, publicPath } = data;
const assets = entrypoints[bundle].assets;
for (let i = 0; i < assets.length; i++) {
await runScript(publicPath + assets[i]).then(() => {
if (i === assets.length - 1) {
resolve()
}
})
}
});
singleSpa.registerApplication( //注冊(cè)微前端服務(wù)
'cv',
async () => {
// 注冊(cè)用函數(shù)倡蝙,
// return 一個(gè)singleSpa 模塊對(duì)象九串,模塊對(duì)象來(lái)自于要加載的js導(dǎo)出
// 如果這個(gè)函數(shù)不需要在線引入,只需要本地引入一塊加載:
// () => import('xxx/main.js')
let singleVue = null;
await getManifest('http://localhost:3000/manifest.json', 'app').then(() => {
singleVue = window.singleVue;
});
return singleVue;
},
location => location.pathname.startsWith('/cv/') // 配置微前端模塊前綴
);
singleSpa.registerApplication( //注冊(cè)微前端服務(wù)
'lb',
async () => {
let singleVue = null;
await getManifest('http://localhost:5000/manifest.json', 'app').then(() => {
singleVue = window.singleVue;
});
return singleVue;
},
location => location.pathname.startsWith('/lb/') // 配置微前端模塊前綴
);
singleSpa.start(); // 啟動(dòng)
3寺鸥、在路由中注冊(cè)統(tǒng)一路由猪钮,我們注冊(cè)一個(gè)子服務(wù)路由,可填不填寫(xiě)component字段胆建。
{
path: '/cv',
name: 'cv',
component: () => import(/* webpackChunkName: "about" */ '@/components/child.vue')
},
child.vue文件
<script>
export default {
name: 'Vue',
render (h) {
return h()
}
}
</script>
App.vue 增加一個(gè) 子項(xiàng)目dom 的 id
// 點(diǎn)擊路由跳轉(zhuǎn)
<router-link to="/lb/" class="ml10">lb</router-link>
// 子項(xiàng)目id
<div id="childApp"></div>
<router-view />
子項(xiàng)目創(chuàng)建
1躬贡、安裝single-spa-vue依賴(lài)npm install single-spa-vue --save -d
在mian.js中引入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './vuex/store'
import singleSpaVue from 'single-spa-vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
Vue.use(ElementUI);
const errorHandler = (error, vm) => {
console.error('拋出全局異常', error);
}
Vue.config.errorHandler = errorHandler;
Vue.prototype.$throw = (error) => errorHandler(error, this);
const vueOptions = {
el: '#childApp',
router,
store,
render: h => h(App)
}
// 判斷當(dāng)前頁(yè)面使用singleSpa應(yīng)用,不是就渲染
if (!window.singleSpaNavigate) {
delete vueOptions.el
new Vue(vueOptions).$mount('#app')
}
// singleSpaVue包裝一個(gè)vue微前端服務(wù)對(duì)象
const vueLifecycles = singleSpaVue({
Vue,
appOptions: vueOptions
})
export const bootstrap = vueLifecycles.bootstrap // 啟動(dòng)時(shí)
export const mount = vueLifecycles.mount // 掛載時(shí)
export const unmount = vueLifecycles.unmount // 卸載時(shí)
export default vueLifecycles
2、安裝stats-webpack-plugin插件npm install stats-webpack-plugin --save -d
vue.config.js
const StatsPlugin = require('stats-webpack-plugin');
module.exports = {
publicPath: '//localhost:5000',
// css在所有環(huán)境下眼坏,都不單獨(dú)打包為文件拂玻。這樣是為了保證最小引入(只引入js)
css: {
extract: false
},
configureWebpack: (config) => {
if (env === 'production') {
config.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
compress: {
// warnings: false,
drop_debugger: true, // console
drop_console: true,
pure_funcs: ['console.log'] // 移除console
}
}
})
);
}
config.plugins.push(
new StatsPlugin('manifest.json', {
chunkModules: false,
entrypoints: true,
source: false,
chunks: false,
modules: false,
assets: false,
children: false,
exclude: [/node_modules/]
}))
config.output.library = 'singleVue'
config.output.libraryTarget = 'window'
},
devtool: 'none'
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 5000,
headers: {"Access-Control-Allow-Origin":"*"} //本地跨域處理
}
}
3酸些、router 配置
const router = new VueRouter({
mode: 'history',
base: '/cv/',
routes
})