三、如何手动实现一个微前端框架雏形
如何手動實現一個微前端框架雛形
一、了解微前端
1. 什么是微前端
為了解決一整塊兒龐大的前端服務所帶來的變更和拓展方面的限制,將整體前端服務拆分成一些更小、更簡單的,能夠獨立開發、測試部署的小塊兒。但是在整體表現上還是一個整體的產品的服務稱為微前端。
2. 為什么要學習微前端
2.1 關鍵優勢
每個分模塊的規模更小,更利于維護
松散各個模塊之間的耦合。
可以實現增量升級,避免在重構的時候影響整體邏輯
技術棧無關,可以在每個子模塊之間選取合適的技術棧進行開發
獨立開發獨立部署
2.2 為什么要學
在重構項目的時候,總會有各種各樣的問題,如
項目技術棧落后,重構時混用多種技術棧,導致項目技術?;祀s。
各個模塊之間耦合嚴重,動一處,可能影響整體項目運轉
因為各種歷史問題不得不做出各種妥協,或者是添加各種兼容條件限制。
當你也有以上問題的時候,不妨考慮使用微前端,不僅可以拜托繁重的歷史包袱,讓你可以進行輕松重構,而且不會出現重構不徹底的情況,可以根據需求的實際情況進行重構工作,而不是基于項目歷史債務的問題進行考慮。
這是需要學習微前端一個很重要的前提,如果你的項目沒有任何歷史包袱,或者說項目是從零開始的,這樣就不推薦你引入微前端這個東西,這樣或許不能達到預期的目的,或許只會加重自己的開發負擔。
3. 手寫一個框架可以給我們帶來什么
可以從框架作者的角度去考慮,為什么框架的架構要這么設計,從中學習作者的設計思想,對于模型概念的理解。
二、微前端實現方式對比
1.iframe
優勢:
天生支持沙箱隔離、獨立運行,這是最大的優勢。不用做任何沙箱的處理。
劣勢:
無法預加載緩存 iframe
無法共享基礎庫
事件通信限制較多
快捷鍵劫持
事件無法冒泡到頂層
跳轉路徑無法保持統一
登錄狀態無法共享
iframe 加載失敗,主應用無法感知
性能問題難以計算
2.基于 SPA 的微前端架構
優勢
可以規避 iframe 現存的問題點
可緩存和預加載
共享登錄狀態
主應用感知加載狀態
快捷鍵劫持
通信設計
共享基礎庫
劣勢:
實現難度較高。需要實現以下幾項內容
路由系統
沙箱隔離
樣式隔離
通信
html 加載和 js 解析能力
調試開發能力
三、項目介紹
主要用到koa、vue2、vue3、react15、react16
應用:主應用、子應用、后端服務和發布應用
主應用-選定vue3技術棧
vue2子應用:實現新能源頁面
vue3子應用:首頁、選車
react15子應用:資訊、視頻、視頻詳情
react16子應用:新車、排行、登錄
服務端接口:koa實現
發布應用:express
service
npm install koa-generator -g koa -v Koa2 service // 監聽修改文件自動重啟 npm install supervisor —save-dev 處理跨域問題 npm install koa2-cors —save-devbuild>run.js快速啟動所有的應用
四、子應用接入微前端
子應用接入微前端-vue2
// 1. vue2 > vue.config.js,子應用設置允許跨域,主應用需要獲取子應用內容,防止資源攔截devServer: {contentBase: path.join(__dirname, 'dist'), // contentBase必須要配置hot: false,disableHostCheck: true,port,headers: {'Access-Control-Allow-Origin': '*', // 本地服務的跨域內容},},// 自定義webpack配置configureWebpack: {resolve: {alias: {'@': resolve('src'),},},output: {// library配置vue2后瀏覽器可以通過window.vue2獲取到打包的內容,之后在微前端框架里也會用到這個信息,這個配置成子應用的名稱library: `${packageName}`,// 把子應用打包成 umd 庫格式 commonjs 瀏覽器,node環境libraryTarget: 'umd',},},2. //vue2 > main.js 配置如果不是微前端環境下才執行render函數,微前端環境下需要根據微前端生命周期觸發函數,暴露一組生命周期,window.vue2里會有這幾個生命周期內容,后續會在微前端框架里使用,生命周期何時執行,需要在微前端框架里進行控制const render = () => {new Vue({router,render: h => h(App)}).$mount('#app-vue') }if (!window.__MICRO_WEB__) {render() } // 一般不做處理,特殊情況,例如加載之前需要做參數的處理再處理 export async function bootstrap() {console.log('bootstrap'); } // 調用render方法,render方法執行成功之后就可以得到我們的整體vue2項目的vue實例,用實例就可以做一些其他東西 export async function mount() {render() } // 處理卸載上的事,如撤銷監聽事件,撤銷這個容器顯示的所有內容 export async function unmount(ctx) {const { container } = ctxif (container) {document.querySelector(container).innerHTML = ''} }子應用接入微前端 - vue3
配置與vue2同理
子應用接入微前端 - react15
output: {path: path.resolve(__dirname, 'dist'),filename: 'react15.js',library: 'react15',libraryTarget: 'umd',umdNamedDefine: true,publicPath: 'http://localhost:9002/'},devServer: {// 配置允許跨域headers: { 'Access-Control-Allow-Origin': '*' },contentBase: path.join(__dirname, 'dist'),compress: true,port: 9002,historyApiFallback: true,hot: true,}const render = () => {ReactDOM.render((<BasicMap />), document.getElementById('app-react')) }if (!window.__MICRO_WEB__) {render() }export const bootstrap = () => {console.log('bootstrap') }export const mount = () => {render() }export const unmount = () => {console.log('卸載')// 可以通過index.html里的根結點根元素下直接置空,或者將傳入的容器內容置空 }子應用接入微前端 - react16
webpack打包回打包成
(function(){……})()
配置library之后會打包成
var react16 = (function(){……})()
當前變量內容是存在全局的
五、微前端框架開發
主框架—子應用注冊
// main > src > components > MainNav.vue導航跳轉時要跳轉對應的鏈接,用useRouter, useRoute// main > src > router > index.js,outer路由里配置react15、react16、vue2、vue3對應的組件都設置成app.vue const routes = [{path: '/',component: () => import('../App.vue'),},{path: '/react15',component: () => import('../App.vue'),},{path: '/react16',component: () => import('../App.vue'),},{path: '/vue2',component: () => import('../App.vue'),},{path: '/vue3',component: () => import('../App.vue'),}, ];// 1. main>src>main.js import { subNavList } from './store/sub' import { registerApp } from './util' registerApp(subNavList)// 2. main > src > store > sub.js拋出子應用列表 export const subNavList = [{name: 'react15',// 唯一標識entry: '//localhost:9002/', // 去哪個入口獲取到子應用的文件container: '#micro-container', // 子應用渲染容器containeractiveRule: '/react15', // 激活規則,子應用激活的路由},{name: 'react16',entry: '//localhost:9003/',container: '#micro-container',activeRule: '/react16',},{name: 'vue2',entry: '//localhost:9004/',container: '#micro-container',activeRule: '/vue2',},{name: 'vue3',entry: '//localhost:9005/',container: '#micro-container',activeRule: '/vue3',}, ];// 3.main > src > util > index.js里registerApp注冊子應用并調用registerMicroApps注冊到微前端框架里 import { registerMicroApps } from '../../micro' export const registerApp = (list) => {// 注冊到微前端框架里registerMicroApps(list) }// 4.main > micro > start.js有了微前端框架的第一個方法 import { setList } from './const/subApps' export const registerMicroApps = (appList) => {setList(appList) }// 5.main > micro>const>subApps.js在微前端框架里定義了一個subApps去統一一管理子應用列表 let list = []export const getList = () => listexport const setList = appList => list = appList // 通過setList將子應用列表注冊到list上,之后在整體微前端框架運行期間都可以通過getList去獲取微前端框架 - 路由攔截
// 1. main > micro > start.js import { rewriteRouter } from './router/rewriteRouter' // 實現路由攔截 rewriteRouter()// 2.main > micro > router > rewriteRouter重寫路由跳轉微前端框架-獲取首個子應用
// main > src > util > index.js import { registerMicroApps } from '../../micro' export const registerApp = (list) => {// 注冊到微前端框架里registerMicroApps(list)// 開啟微前端框架start() }// main > micro > start.js里寫start函數 import { setList, getList } from './const/subApps' import { currentApp } from './utils' export const start = () => {// 首先驗證當前子應用列表是否為空const apps = getList()if (!apps.length) {// 子應用列表為空throw Error('子應用列表為空, 請正確注冊')}// 有子應用的內容, 查找到符合當前路由的子應用const app = currentApp()const { pathname, hash } = window.locationif (app) {const url = pathname + hashwindow.__CURRENT_SUB_APP__ = app.activeRule // 加對應的標記,之后可以在turnApp里判斷isTurnChild,有變動再進行接下來的操作window.history.pushState('', '', url) // app有內容就觸發pushState方法} }// main > micro > utils > index.js //獲取的規則是window.location.pathname與子應用的activeRule做對比,返回命中的子應用 export const currentApp = () => {const currentUrl = window.location.pathnamereturn filterApp('activeRule', currentUrl) } export const filterApp = (key, value) => {const currentApp = getList().filter(item => item[key] === value)return currentApp && currentApp.length ? currentApp[0] : {} }// main > micro > router > routerHandle.js import { isTurnChild } from '../utils' export const turnApp = async () => {if (isTurnChild()) {console.log('路由切換了')} }// main > micro > utils > index.js // 子應用是否做了切換,有變動才進行接下來的操作 export const isTurnChild = () => {if(window.__CURRENT_SUB_APP__ === window.location.pathname) {return false}return true; }微前端框架主應用生命周期
// main > src > util > index.js的registerMicroApps第二個參數添加生命周期,將生命周期注冊奧微前端框架里 import { registerMicroApps, start } from '../../micro' import { loading } from '../store' export const registerApp = (list) => {// 注冊到微前端框架里registerMicroApps(list, {beforeLoad: [() => {loading.changeLoading(true) // 控制loading狀態console.log('開始加載')}],mounted: [() => {loading.changeLoading(false) // 控制loading狀態console.log('渲染完成')}],destoryed: [() => {console.log('卸載完成')}]})// 開啟微前端框架start() }// 微前端框架中main > micro > start.js里registerMicroApps接收第二個參數 export const registerMicroApps = (appList, lifeCycle) => {setList(appList)setMainLifecycle(lifeCycle) // 設置lifeCycle }// main > micro>const>mainLifeCycle.js let lifecycle = {} export const getMainLifecycle = () => lifecycle export const setMainLifecycle = data => lifecycle = data微前端框架-微前端生命周期
// main > micro > router > routerHandle.js判斷子應用是否切換里執行微前端的生命周期 export const turnApp = async () => {if (isTurnChild()) {// 微前端的生命周期執行await lifecycle()} }// main > micro > lifeCycle > index.js import { findAppByRoute } from '../utils' import { getMainLifecycle } from '../const/mainLifeCycle' export const lifecycle = async () => {// 獲取到上一個子應用const prevApp = findAppByRoute(window.__ORIGIN_APP__)// 獲取到要跳轉到的子應用const nextApp = findAppByRoute(window.__CURRENT_SUB_APP__)if (!nextApp) {return}if (prevApp && prevApp.unmount) {// 其他子應用切換過來的,卸載上一個子應用await destoryed(prevApp)}const app = await beforeLoad(nextApp) // 加載下一個子應用框架await mounted(app) // 渲染 } export const beforeLoad = async (app) => {await runMainLifeCycle('beforeLoad') // 運行主應用的生命周期app && app.beforeLoad && app.beforeLoad() // 運行子應用生命周期內容const appContext = nullreturn appContext } export const mounted = async (app) => {app && app.mount && app.mount()await runMainLifeCycle('mounted') } export const destoryed = async (app) => {app && app.unmount && app.unmount()// 對應的執行以下主應用的生命周期await runMainLifeCycle('destoryed') } export const runMainLifeCycle = async (type) => {const mainlife = getMainLifecycle() // 主應用生命周期是一個數組await Promise.all(mainlife[type].map(async item => await item())) // 需要等到所有內容都執行完成才可以繼續 }// main > micro > utils > index.js export const isTurnChild = () => {window.__ORIGIN_APP__ = window.__CURRENT_SUB_APP__;if(window.__CURRENT_SUB_APP__ === window.location.pathname) {// 如果當前子應用沒有變動,返回的是false,window.__ORIGIN_APP__ 與window.__CURRENT_SUB_APP__是相同的return false}// 如果當前子應用有變動,需要對window.__CURRENT_SUB_APP__進行更換// 這樣就可以獲取上一個子應用和下一個子應用window.__CURRENT_SUB_APP__ = window.location.pathnamereturn true; }// main > micro > utils > index.js export const findAppByRoute = (router) => {return filterApp('activeRule', router) } export const filterApp = (key, value) => {const currentApp = getList().filter(item => item[key] === value)return currentApp && currentApp.length ? currentApp[0] : {} }獲取需要展示的頁面 - 加載和解析html
//訪問子應用http://localhost:9005/#/, f12發現有個get請求,get請求路徑就是子應用路口// main > micro > lifeCycle > index.js的beforeLoad 里執行loadHtml import { loadHtml } from '../loader' export const beforeLoad = async (app) => {await runMainLifeCycle('beforeLoad')app && app.beforeLoad && app.beforeLoad()const subApp = await loadHtml(app) // 獲取的是子應用的內容subApp && subApp.beforeLoad && subApp.beforeLoad()return subApp }// main > micro > loader > index.js import { fetchResource } from '../utils/fetchResource' // 加載html的方法 export const loadHtml = async (app) => {// 第一個,子應用需要顯示在哪里let container = app.container // #id 內容// 子應用的入口let entry = app.entryconst html = await parseHtml(entry)const ct = document.querySelector(container)if (!ct) {throw new Error('容器不存在,請查看')}ct.innerHTML = htmlreturn app } export const parseHtml = async (entry, name) => {const html = await fetchResource(entry)return html }// main > micro > utils > fetchResource.js export const fetchResource = url => fetch(url).then(async res => await res.text())// 刷新頁面,頁面是空白的,什么都沒有,在micro-container微前端容器里有子應用的信息,沒有顯示子應用內容是當前js所加載的內容是加載不到的,微前端處理里并沒有獲取js的內容,并沒有執行 // 切換路由,micro-container微前端容器內容會有變化加載和解析js
// main > micro > loader > index.js export const loadHtml = async (app) => {// 第一個,子應用需要顯示在哪里let container = app.container // #id 內容// 子應用的入口let entry = app.entryconst [dom, scripts] = await parseHtml(entry, app.name)const ct = document.querySelector(container)if (!ct) {throw new Error('容器不存在,請查看')}ct.innerHTML = domreturn app } const cache = {} // 根據子應用的name來做緩存 export const parseHtml = async (entry, name) => {if (cache[name]) {return cache[name]}const html = await fetchResource(entry)let allScript = []const div = document.createElement('div')div.innerHTML = html// 接下來針對div這個偽元素做對應的html處理,處理內容包含標簽、link、script(src,js)const [dom, scriptUrl, script] = await getResources(div, entry)const fetchedScripts = await Promise.all(scriptUrl.map(async item => fetchResource(item)))allScript = script.concat(fetchedScripts)cache[name] = [dom, allScript]return [dom, allScript] } export const getResources = async (root, entry) => {const scriptUrl = [] // js 鏈接 src hrefconst script = [] // 寫在script中的js腳本內容const dom = root.outerHTML// 深度解析function deepParse(element) {const children = element.childrenconst parent = element.parent;// 第一步處理位于 script 中的內容if (element.nodeName.toLowerCase() === 'script') {const src = element.getAttribute('src');if (!src) {// script不是通過外部鏈接引用的script.push(element.outerHTML)} else {// scriptUrl要做是否以http開頭的判斷,因為可能子應用沒有配置publicPathif (src.startsWith('http')) {scriptUrl.push(src)} else {scriptUrl.push(`http:${entry}/${src}`)}}if (parent) {parent.replaceChild(document.createComment('此 js 文件已經被微前端替換'), element)}}// link 也會有js的內容if (element.nodeName.toLowerCase() === 'link') {const href = element.getAttribute('href');if (href.endsWith('.js')) {if (href.startsWith('http')) {scriptUrl.push(href)} else {scriptUrl.push(`http:${entry}/${href}`)}}}for (let i = 0; i < children.length; i++) {deepParse(children[i])}}deepParse(root)return [dom, scriptUrl, script] }執行js腳本
// main > micro > utils > index.js 中 // pathname 里符合activeRule的規則 export const isTurnChild = () => {const { pathname } = window.location// 當前路由無改變。let prefix = pathname.match(/(\/\w+)/)if(prefix) {prefix = prefix[0]}window.__ORIGIN_APP__ = window.__CURRENT_SUB_APP__;if (window.__CURRENT_SUB_APP__===prefix) {return false}const currentSubApp = window.location.pathname.match(/(\/\w+)/)if (!currentSubApp) {return false}// 當前路由以改變,修改當前路由window.__CURRENT_SUB_APP__ = currentSubApp[0];return true; }// main > micro > loader > index.js import { performScript } from "../sandbox/performScript"; // 加載html的方法 export const loadHtml = async (app) => {// 第一個,子應用需要顯示在哪里let container = app.container // #id 內容// 子應用的入口let entry = app.entryconst [dom, scripts] = await parseHtml(entry, app.name)const ct = document.querySelector(container)if (!ct) {throw new Error('容器不存在,請查看')}ct.innerHTML = dom // 所有js文件的執行放在dom執行完成之后scripts.forEach(item => {performScript(item)})return app }// main > micro > sandbox > performScript.js // 執行js腳本 export const performScript = (script) => {eval(script)// new Function(script).call(window,window)// 需要設置全局對象,將this指向window,傳入當前的window對象 } eval('var a=1;var b=2;console.log(a+b)') var s = 'return `hello ${name}`' var func = new Function('name', s) func('小明') // “hello 小明”微前端環境變量
// main > micro > loader > index.js import { sandBox } from "../sandbox"; // 加載html的方法 export const loadHtml = async (app) => {// 第一個,子應用需要顯示在哪里let container = app.container // #id 內容// 子應用的入口let entry = app.entryconst [dom, scripts] = await parseHtml(entry, app.name)const ct = document.querySelector(container)if (!ct) {throw new Error('容器不存在,請查看')}ct.innerHTML = domscripts.forEach(item => {sandBox(app, item)})return app }// main > micro > sandbox > index.js // 子應用生命周期處理, 環境變量設置 export const sandBox = (app, script) => {// 1. 設置環境變量window.__MICRO_WEB__ = true// 2. 運行js文件// 不僅僅執行了子應用腳本,執行完成之后也獲取到子應用生命周期const lifecycle = performScriptForEval(script, app.name)// 運行完js后需要得到生命周期內容,將所有的生命周期函數掛載到app上,掛載完成后就可以在微前端框架lifeCycle里獲取到app的生命周期內容并執行if (isCheckLifeCycle(lifecycle)) {app.bootstrap = lifecycle.bootstrapapp.mount = lifecycle.mountapp.unmount = lifecycle.unmount} } const isCheckLifeCycle = lifecycle => lifecycle &&lifecycle.bootstrap &&lifecycle.mount &&lifecycle.unmount// main > micro > sandbox > performScript.js export const performScriptForEval = (script, appName) => {// 之前配置的library可以獲取window.appName有生命周期函數const scriptText = `() => {${script}return window['${appName}'] }`return eval(scriptText).call(window,window)// app module mount } export const performScriptForFunction = (script, appName) => {const scriptText = `${script}return window['${appName}']`return new Function(scriptText).call(window,window) }運行環境隔離 - 快照沙箱
// 為什么要隔離運行環境 //如在vue3>main.js的mount中設置window.a=1;在加載應用時,切換到其他子應用window.a還存在,這樣對公共的變量沒問題,但是如果變量只在某個子應用里應用,切換到其他應用變量還存在對邏輯獲取、變量設置都會有影響,所以我們需要將運行時變量維護在子應用里,切換子應用變量消失掉;如果有子應用公共的變量,可以放在主應用里,或者通過主應用的方法設置到全局上 //如何實現將我們的子應用運行在沙箱環境中 // main > micro > sandbox > snapShotSandbox.js // 快照沙箱:針對于給當前的全局變量實現一個快照的方式來記錄我們沙箱的內容,在子應用切換后將所有沙箱的變量設為初始值 // 消耗和執行性能都是比較差的,一個window上會掛很多屬性, // 應用場景:比較老版本的瀏覽器, export class SnapShotSandbox {constructor() {// 1. 代理對象this.proxy = window // 之后就可以使用proxy這個代理對象完成全局對象的替換this.active()}// 沙箱激活active() {// 創建一個沙箱快照this.snapshot = new Map()// 遍歷全局環境for(const key in window) {this.snapshot[key] = window[key] // 將window所有的key值記錄在快照對象上}}// 沙箱銷毀inactive () {for (const key in window) {if (window[key] !== this.snapshot[key]) {// 還原操作window[key] = this.snapshot[key]}}} }// main > micro > sandbox > index.js import { performScriptForEval } from './performScript' import { SnapShotSandbox } from './snapShotSandbox' // 子應用生命周期處理, 環境變量設置 export const sandBox = (app, script) => {const proxy = new SnapShotSandbox() // 記錄所有的window值,激活沙箱if (!app.proxy) {app.proxy = proxy // proxy掛載到app上}// 1. 設置環境變量window.__MICRO_WEB__ = true// 2. 運行js文件,需要傳遞全局對象app.proxy.proxy,之后所有的運行環境都在代理對象里const lifecycle = performScriptForEval(script, app.name, app.proxy.proxy)// 生命周期,掛載到app上if (isCheckLifeCycle(lifecycle)) {app.bootstrap = lifecycle.bootstrapapp.mount = lifecycle.mountapp.unmount = lifecycle.unmount} }// main > micro > sandbox > performScript.js,接收global參數,代替window進行執行 export const performScriptForEval = (script, appName,global) => {// 之前配置的library可以獲取window.appName有生命周期函數const scriptText = `() => {${script}return window['${appName}'] }`return eval(scriptText).call(global,global)// app module mount } export const performScriptForFunction = (script, appName,global) => {const scriptText = `${script}return window['${appName}']`return new Function(scriptText).call(global,global) }// main > micro > lifeCycle > index.js中將代理銷毀 export const lifecycle = async () => {// 獲取到上一個子應用const prevApp = findAppByRoute(window.__ORIGIN_APP__)// 獲取到要跳轉到的子應用const nextApp = findAppByRoute(window.__CURRENT_SUB_APP__)if (!nextApp) {return}if (prevApp && prevApp.unmount) {if (prevApp.proxy) {prevApp.proxy.inactive() // 將沙箱銷毀}await destoryed(prevApp)}const app = await beforeLoad(nextApp)await mounted(app) } // 運行時變量維護在子應用里,子應用公共變量放在主應用里,或者可以通過主應用方法設在全局里 // 如何將子應用運行在沙箱環境中 // 要設置一個沙箱環境在運行整體js時就需要將沙箱環境給設置上 // 創建一個文件snapShotSandbox快照沙箱,針對給當前全局變量實現一個快照的方式,來記錄我們沙箱的內容,在子應用切換之后,將所有沙箱的變量置為初始值 // 在生命周期上一個子應用銷毀前將沙箱環境重置 // Window.a只在當前子應用生效運行環境隔離 - 代理沙箱
// 快照沙箱是不支持多實例的,同一時間我們的頁面只可以顯示一個子應用,如果一個頁面需要顯示多個子應用快照沙箱不支持,要用代理沙箱 // 對于Proxy可以查下具體文檔的使用,可以將它代理的對象做個攔截,我們之后對代理的對象做任何操作都在它攔截上處理一次,舉個例子,Proxy可以做到13種攔截,下面舉get和set例子 let a = {} const proxy = new Proxy(a, {get() {console.log(111)},set(){console.log(222)return true} }) console.log(proxy.b) proxy.a = 1 // 結果為111 undefined 222,proxy.b獲取proxy上屬性會受到get方法的攔截,會先執行get方法,返回111,proxy.b并沒有返回任何數據輸出undefined,proxy.a = 1賦值的操作觸發了set操作,輸出222 // 如果get方法return 333;console.log(proxy.b)都會返回333 // main > micro > sandbox > proxySandbox.js let defaultValue = {} // 子應用的沙箱容器 export class ProxySandbox{constructor() {this.proxy = null;this.active()}// 沙箱激活active() {// 子應用需要設置屬性,this.proxy = new Proxy(window, {get(target, key) {// 處理Illegal invocation非法操作if (typeof target[key] === 'function') {return target[key].bind(target)}return defaultValue[key] || target[key] // 做兼容操作,如果defaultValue找不到去target上找,比如location},set(target, key, value) {defaultValue[key] = valuereturn true}})}// 沙箱銷毀inactive () {defaultValue = {}} }// main > micro > sandbox > index.js中使用ProxySandbox import { performScriptForEval } from './performScript' import { ProxySandbox } from './proxySandbox' // 子應用生命周期處理, 環境變量設置 export const sandBox = (app, script) => {const proxy = new ProxySandbox() // 記錄所有的window值,激活沙箱if (!app.proxy) {app.proxy = proxy // proxy掛載到app上}// 1. 設置環境變量window.__MICRO_WEB__ = true// 2. 運行js文件,需要傳遞全局對象app.proxy.proxy,之后所有的運行環境都在代理對象里const lifecycle = performScriptForEval(script, app.name, app.proxy.proxy)// 生命周期,掛載到app上if (isCheckLifeCycle(lifecycle)) {app.bootstrap = lifecycle.bootstrapapp.mount = lifecycle.mountapp.unmount = lifecycle.unmount} }// main > micro > sandbox > performScript.js // 執行js腳本 export const performScriptForFunction = (script, appName, global) => {window.proxy = globalconsole.log(global)const scriptText = `return ((window) => {${script}return window['${appName}']})(window.proxy)`return new Function(scriptText)() } export const performScriptForEval = (script, appName, global) => {// library window.appNamewindow.proxy = globalconst scriptText = `((window) => {${script}return window['${appName}'] })(window.proxy)`return eval(scriptText)// app module mount } // 在vue3路由獲取window.a是undefined,vue3對window的操作并沒有作用到我們全局的window對象上,而是作用到代理沙箱里// 報Illegal invocation非法操作 const proxy = new Proxy(window,{})// 通過代理對象代理了window,但是沒有傳遞任何方式,那所有的操作都不會經過代理 proxy.addEventListener('a',()=>{console.log(1) }) // addEventListener并不是指向window,而是指向proxy內容,在正常處理回調函數和添加監聽事件時會有很多問題,這使需要對它get做些特殊的操作 const proxy = new Proxy(window,{get(target, key) {if (typeof target[key] === 'function') {return target[key].bind(target)// 得到this指向target指向window的函數。才可以正常使用原生的一些方法}}, })css樣式隔離
// 1.css modules在子應用里配置css-loader設置module為true // 2.shadow dom,通過mode-attachShadow方法,這是比較新的語法,對瀏覽器兼容性支持性不是很高,將我們的元素、樣式統一隔離到虛擬的dom上,這個dom集中我們所有的內容,和其他內容沒有任何沖突的 const box1 = document.getElementById('box1') // 開啟shadow dom模式 const shadow1 = box1.attachShadow({mode:'open'}) const one = document.createElement('div') one.className = 'one' one.innerText = '第一個內容' const style1 = document.createElement('style') style1.textContent = ` .one{color:red; } ` shadow1.appendChild(one1); shadow1.appendChild(style1);const box2 = document.getElementById('box2') // 開啟shadow dom模式 const shadow2 = box2.attachShadow({mode:'open'}) const two = document.createElement('div') two.className = 'one' two.innerText = '第一個內容' const style2 = document.createElement('style') style2.textContent = ` .one{color:blue; } ` shadow2.appendChild(one2); shadow2.appendChild(style2); // 第一個第二個同時位于#shadow-root下,類名一樣,同樣的元素位于不同的shadow-root下,他們的樣式和內容不會發生沖突 // 3.minicss:minicssectractplugin,把所有css打包成單獨的css文件,然后渲染子應用時會通過link標簽引入我們的css文件,文件的引用是放在子應用容器,切換子應用時把容器內的所有內容清空,對于css文件的引入也是清空的,不會存在兩個子應用樣式相互影響的問題 const MiniCssExtractPlugin = require('mini-css-extract-plugin') {test: /\.(cs|scs)s$/,use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'] }, // 4.css-in-js,css內容通過js進行設置,每一個子應用的css都位于js文件里,如果清空了所有子應用內容,也就清空了css的樣式應用間通信 - 父子通信
如登錄狀態父子應用不同步問題,主應用狀態變更可以通過某種方法及時通知我們的子應用,子應用狀態變更也要通過方法通知主應用進行修改
//應用間通信主要有以下兩種方式 // 1.props(主要) // 訪問http://localhost:8080/react16#/login時,頭部與導航不需要 // main>src>store>header.js import { ref } from 'vue'; export const headerStatus = ref(true) export const changeHeader = type => headerStatus.value = type;// main>src>store>nav.js import { ref } from 'vue'; export const navStatus = ref(true) export const changeNav = type => navStatus.value = type;// main>src>store>index.js // 暴露header的方法 export * as header from './header' // 暴露nav的方法 export * as nav from './nav'// main>src>App.vue狀態控制導航顯示隱藏 // 如何在子應用里(如react16里)修改主應用導航和頭部的顯示,需要將所有內容通過props傳遞給你子應用 // main > src > store > sub.js中引入store,將appInfo賦值到每一個子應用上 import { loading } from '../store' import * as appInfo from '../store' export const subNavList = [{name: 'react15',// 唯一entry: '//localhost:9002/',loading,container: '#micro-container',activeRule: '/react15',appInfo,},{name: 'react16',entry: '//localhost:9003/',loading,container: '#micro-container',activeRule: '/react16',appInfo,},{name: 'vue2',entry: '//localhost:9004/',loading,container: '#micro-container',activeRule: '/vue2',appInfo,},{name: 'vue3',entry: '//localhost:9005/',loading,container: '#micro-container',activeRule: '/vue3',appInfo,}, ]; // 微前端框架對于子應用的處理基本集中在main>micro>lifeCycle>index.js里,執行里app所有的生命周期,獲取里dom結構,加載里資源,接下來需要在對應生命周期里來將app信息傳遞給子應用里,在執行子應用app.mount的時候將appInfo傳遞過去 // main>src>util>index.js的registerApp注冊子應用的方法里將store內容傳遞給子應用 export const mounted = async (app) => {app && app.mount && app.mount({appInfo: app.appInfo,entry: app.entry})await runMainLifeCycle('mounted') }// react16>src>index.js接下來就可以在子應用react16的mounted事件里獲取到主應用的內容 export const mount = (app) => {app.appInfo.header.changeHeader(false)app.appInfo.nav.changeNav(false)render() }//對于react16而言,只需要在登錄頁面進行隱藏,目前其他頁面也是隱藏的 // react16>src>utils>main.js對app做個緩存 let main = null export const setMain = (data) => {main = data } export const getMain = () => {return main }// react16>src>index.js中將app設置在main對象上 import {setMain} from './src/utils/main'; export const mount = (app) => {setMain(app)render() }//react16>src>pages>login>index.jsx中隱藏,登錄頁面隱藏,其他頁面還是顯示 import { getMain } from '../../utils/main'useEffect(() => {// 不僅僅可以獲取到主應用方法,同時也可以通過方法向主應用傳遞我們的參數const main = getMain()main.appInfo.header.changeHeader(false)main.appInfo.nav.changeNav(false)}, [])// 好萊塢原則 - 不用聯系我,當我需要的時候會打電話給你 // 依賴注入 - 主應用的顯示隱藏,注入到子應用內部,通過子應用內部的方法進行調用// 2.customevent //main>micro>customevent>index.js export class Custom {// 事件監聽on (name, cb) {window.addEventListener(name, (e) => {cb(e.detail)})}// 事件觸發emit(name, data) {const event = new CustomEvent(name, {detail: data})window.dispatchEvent(event)} }//main>micro>start.js import { Custom } from './customevent' const custom = new Custom() custom.on('test', (data) => {console.log(data) }) window.custom = custom// vue3>src>main.js export const mount = () => {window.custom.emit('test',{a:1})render() } //可以看到打印的a:1,子應用向主應用傳遞事件,同樣道理也可以從主應用向子應用發送事件,但是一定要注意監聽和觸發的時機,監聽一定要在觸發之前,否則會產生一些監聽不到的問題應用間通信 - 子應用間通信
對于微前端而言,需要獲取上一個應用的內容,表明當前的應用設計是有一些缺陷的,理論上來說,我們每一個應用之間都不會依賴于上一個或者下一個應用間的信息,這些信息我們都可以通過主應用或者數據服務來獲取,但也避免不了一些及其特殊的情況,我們需要用到上一個子應用處理過的信息,在這子應用里做其他處理
// 1.props // 子應用1 - 父應用交互 - 子應用2,子應用1和父應用進行交互,得到子應用1傳遞的參數,父應用與子應用2進行交互,將子應用1傳遞的參數通過父應用的轉發傳遞給子應用2 // 2.customevent // 例如vue3與vue2進行通信 //vue3>src>main.js export const mount = () => {window.custom.on('test1',(data)=>{console.log(data)})render() }//vue2>src>main.js觸發一個事件將參數傳遞到vue3里 export const mount = () => {window.custom.emit('test1',{a:1})render() } // vue3切換到vue2子應用里會打印a:1對象//如果需要從vue3向vue2發傳遞數據 //vue2>src>main.js export const mount = () => {window.custom.on('test2',(data)=>{console.log(data,'======')})window.custom.emit('test1',{a:1})render() } //vue3>src>main.js export const mount = () => {//先有監聽再有觸發window.custom.on('test1',(data)=>{window.custom.emit('test2',{b:2})})render() } // vue3切換到vue2頁面,b:2 //vue2子應用里先做里test2的監聽,再做了test1的觸發,在vue3里只要接收到了test1的事件,之后我們就可以在它回調函數里將test2事件進行觸發并且傳遞我們需要的參數 //從vue3向vue2傳遞數據,下一個子應用是沒有加載過的,沒有自己的監聽事件,如果在vue3里直接做了test2事件的觸發,就會出現在vue2監聽不到的情況,需要在vue2里添加test2的監聽事件,添加完成之后向vue3發一個事件,告訴它你現在可以觸發test2的事件了,這樣在vue3里做事件的觸發,先監聽test1,回調函數里觸發test2全局狀態管理 - 全局store
//上節講到的監聽如果當前監聽的方法非常多,會出現監聽方法重疊,需要做到name的唯一化管理,極大提升開發難度,所以我們需要一個管理系統,不需要定義我們監聽的事件,也可以觸發我們所有監聽的內容 //main>micro>store>index.js export const createStore = (initData = {}) => (() => {let store = initDataconst observers = [] // 管理所有的訂閱者,依賴// 獲取storeconst getStore = () => store// 更新storeconst update = (value) => {if (value !== store) {// 執行store的操作const oldValue = store// 將store更新store = value// 通知所有的訂閱者,監聽store的變化observers.forEach(async item => await item(store, oldValue))}}// 添加訂閱者const subscribe = (fn) => {observers.push(fn)}return {getStore,update,subscribe,} })() //在微前端框架里實現這樣的狀態管理,與所有的框架都是沒有關系的,每套框架都可以使用這套狀態管理體系來做//main>src>utils>index.js import { createStore } from '../../micro' const store = createStore() window.store = store store.subscribe((newValue, oldValue) => {console.log(newValue, oldValue, '---') }) // 添加訂閱者//vue3>src>main.js export async function mount(app) {const storeData = window.store.getStore() // 獲取默認的data//更新數據,更新完成后會通知訂閱者window.store.update({...storeData, // store里是完全做替換的,需要將之前所有數據傳遞過去a:11})render(); }// 好處: //1.不使用任何的eventName就可以做到事件監聽 //2.同個事件可以添加很多observers,添加狠多訂閱者,之后通過訂閱者來遍歷,修改所有我們的訂閱者依賴 //沒有之前所說的命名會重復的問題,但是也要注意添加訂閱者和update操作也有先后順序,只有先添加訂閱者在操作之后才可以通知到訂閱者,如果沒有添加訂閱者直接進行update操作可以通知到其他訂閱者,但是你當前需要的數據沒有了提高加載性能 - 應用緩存
// main > micro > loader > index.js里加載過的資源不再進行加載 export const loadHtml = async (app) => {// 第一個,子應用需要顯示在哪里let container = app.container // #id 內容// 子應用的入口let entry = app.entryconst [dom, scripts] = await parseHtml(entry, app.name)const ct = document.querySelector(container)if (!ct) {throw new Error('容器不存在,請查看')}ct.innerHTML = domreturn app } const cache = {} // 根據子應用的name來做緩存 export const parseHtml = async (entry, name) => {if (cache[name]) {return cache[name]}const html = await fetchResource(entry)let allScript = []const div = document.createElement('div')div.innerHTML = html// 接下來針對div這個偽元素做對應的html處理,處理內容包含標簽、link、script(src,js)const [dom, scriptUrl, script] = await getResources(div, entry)const fetchedScripts = await Promise.all(scriptUrl.map(async item => fetchResource(item)))allScript = script.concat(fetchedScripts)cache[name] = [dom, allScript] // return [dom, allScript] } // 節省了很多解析子應用資源的步驟,省了解析和加載的步驟提高加載性能 - 預加載子應用
// main>micro>start.js import { prefetch } from './loader/prefetch' // 啟動微前端框架 export const start = () => {// 首先驗證當前子應用列表是否為空const apps = getList()if (!apps.lenth) {// 子應用列表為空throw Error('子應用列表為空, 請正確注冊')}// 有子應用的內容, 查找到符合當前路由的子應用const app = currentApp()const { pathname, hash } = window.locationif (!hash) {// 當前沒有在使用的子應用// 1. 拋出一個錯誤,請訪問正確的連接// 2. 訪問一個默認的路由,通常為首頁或登錄頁面window.history.pushState(null, null, '/vue3#/index')}if (app && hash) {const url = pathname + hashwindow.__CURRENT_SUB_APP__ = app.activeRulewindow.history.pushState('', '', url)}// 預加載 - 加載接下來的所有子應用,但是不顯示prefetch() }// main>micro>loader>prefetch.js import { getList } from '../const/subApps'; import { parseHtml } from './index'; export const prefetch = async () => {// 1. 獲取到所有子應用列表 - 不包括當前正在顯示的const list = getList().filter(item => !window.location.pathname.startsWith(item.activeRule))// 2. 預加載剩下的所有子應用await Promise.all(list.map(async item => await parseHtml(item.entry, item.name))) }六、框架發布 – 通過npm發布框架
如果其他主應用也想用微前端框架,只能copy過去使用,這樣效率慢,準確性得不到保障,如果微前端框架需要升級,維護起來麻煩,每一份主應用都需要更改,可以將框架通過npm發布,以后主應用通過npm安裝依賴就行
// 1.需要有自己的npm賬號 // 2.npm login // 3.npm whoami 查看當前登錄的賬號 // 4.npm publish發布 // 5.npm unpublish 包名@版本號 取消發布 npm unpublish 包名@1.0.1 // 主版本號 1 做了不會向下兼容的改動npm version major // 次版本號 0 做了會向下兼容的功能新增 npm version minor(次版本號會遞增,修訂號歸0) // 修訂號 0 做了會向下兼容的問題修正 npm version patch七、應用部署 - 創建自動部署平臺
// npm install express express-generator -g // express -e server // Npm install supervisor —save-dev實現自動更新八、實現應用的自動化部署
九、質量保證 - 如何實現主子應用測試
// 1.訪問到線上或者測試環境 // 2.需要將對應的請求鏈接(頁面請求鏈接)代理到本地 // 3.需要確保本地服務開啟 // Charles // 1.proxy》macOS Proxy開啟 // 2.proxy>ssl proxying settings添加*:443 // 3.proxy>recording settings中include添加* // 4.需要安裝https證書,并且設置為信任狀態help》ssl proxying〉install Charles root certificate // 5.tools》map remote勾選enable map remote十、使用qiankun重構項目
真正想在生辰環境實現一個微前端框架,要做的事情是很多的,要經過大量的試錯,驗證來驗證自己的框架是沒有問題的,現在有很多成熟的微前端框架,我們可以直接用
qiankun源碼分析-應用注冊
十一、使用single-spa重構項目
single-spa.js.org
qiankun與single-spa
總結
以上是生活随笔為你收集整理的三、如何手动实现一个微前端框架雏形的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对话周枫:发布教育领域垂直大模型“子曰”
- 下一篇: 微信接口请求问题