微前端无界机制浅析
简介随着项目的发展,前端SPA应用的规模不断加大、业务代码耦合、编译慢,导致日常的维护难度日益增加。同时前端技术的发展迅猛,导致功能扩展吃力,重构成本高,稳定性低。
为了能够将前端模块解耦,通过相关技术调研,最终选择了无界微前端框架作为物流客服系统解耦支持。为了更好的使用无界微前端框架,我们对其运行机制进行了相关了解,以下是对无界运行机制的一些认识。
基本用法
主应用配置
import WujieVue from 'wujie-vue2';
const { setupApp, preloadApp, bus } = WujieVue;
/*设置缓存*/
setupApp({
});
/*预加载*/
preloadApp({
name: 'vue2'
})
<WujieVue width="100%" height="100%" name="vue2" :url="vue2Url" :sync="true" :alive="true"></WujieVue4-3,降级模式localGenerator
import Vue from "vue";
import { bus, preloadApp, startApp as rawStartApp, destroyApp, setupApp } from "wujie";
const wujieVueOptions = {
name: "WujieVue",
props: {
/*传入配置参数*/
},
data() {
return {
startAppQueue: Promise.resolve(),
};
},
mounted() {
bus.$onAll(this.handleEmit);
this.execStartApp();
},
methods: {
handleEmit(event, ...args) {
this.$emit(event, ...args);
},
async startApp() {
try {
// $props 是vue 2.2版本才有的属性,所以这里直接全部写一遍
await rawStartApp({
name: this.name,
url: this.url,
el: this.$refs.wujie,
loading: this.loading,
alive: this.alive,
fetch: this.fetch,
props: this.props,
attrs: this.attrs,
replace: this.replace,
sync: this.sync,
prefix: this.prefix,
fiber: this.fiber,
degrade: this.degrade,
plugins: this.plugins,
beforeLoad: this.beforeLoad,
beforeMount: this.beforeMount,
afterMount: this.afterMount,
beforeUnmount: this.beforeUnmount,
afterUnmount: this.afterUnmount,
activated: this.activated,
deactivated: this.deactivated,
loadError: this.loadError,
});
} catch (error) {
console.log(error);
}
},
execStartApp() {
this.startAppQueue = this.startAppQueue.then(this.startApp);
},
destroy() {
destroyApp(this.name);
},
},
beforeDestroy() {
bus.$offAll(this.handleEmit);
},
render(c) {
return c("div", {
style: {
width: this.width,
height: this.height,
},
ref: "wujie",
});
},
};
const WujieVue = Vue.extend(wujieVueOptions);
WujieVue.setupApp = setupApp;
WujieVue.preloadApp = preloadApp;
WujieVue.bus = bus;
WujieVue.destroyApp = destroyApp;
WujieVue.install = function (Vue) {
Vue.component("WujieVue", WujieVue);
};
export default WujieVue;实例化化主要是建立起js运行时的沙箱iframe, 通过非降级模式下proxy和降级模式下对document,location,window等全局操作属性的拦截修改将其和对应的js沙箱操作关联起来
5 importHTML入口文件解析
importHtml方法(entry.ts)
import { defineWujieWebComponent } from "./shadow";
// 定义webComponent容器
defineWujieWebComponent();
// 定义webComponent存在shadow.ts 文件中
export function defineWujieWebComponent() {
class WujieApp extends HTMLElement {
connectedCallback(){
if (this.shadowRoot) return;
const shadowRoot = this.attachShadow({ mode: "open" });
const sandbox = getWujieById(this.getAttribute(WUJIE_DATA_ID));
patchElementEffect(shadowRoot, sandbox.iframe.contentWindow);
sandbox.shadowRoot = shadowRoot;
}
disconnectedCallback() {
const sandbox = getWujieById(this.getAttribute(WUJIE_DATA_ID));
sandbox?.unmount();
}
}
customElements?.define("wujie-app", WujieApp);
}importHTML结构如图:
注意点: 通过Fetch url加载子应用资源,这里也是需要子应用支持跨域设置的原因
6 CssLoader和样式加载优化
startApp(options) {
const newSandbox = new WuJie({ name, url, attrs, degradeAttrs, fiber, degrade, plugins, lifecycles });
const { template, getExternalScripts, getExternalStyleSheets } = await importHTML({
url,
html,
opts: {
fetch: fetch || window.fetch,
plugins: newSandbox.plugins,
loadError: newSandbox.lifecycles.loadError,
fiber,
},
});
const processedHtml = await processCssLoader(newSandbox, template, getExternalStyleSheets);
await newSandbox.active({ url, sync, prefix, template: processedHtml, el, props, alive, fetch, replace });
await newSandbox.start(getExternalScripts);
return newSandbox.destroy;
7 子应用active
active方法主要用于做 子应用激活, 同步路由,动态修改iframe的fetch, 准备shadow, 准备子应用注入
7-1, active方法(sandbox.ts)
// wujie
class wujie {
constructor(options) {
/** iframeGenerator在 iframe.ts中**/
this.iframe = iframeGenerator(this, attrs, mainHostPath, appHostPath, appRoutePath);
if (this.degrade) { // 降级模式
const { proxyDocument, proxyLocation } = localGenerator(this.iframe, urlElement, mainHostPath, appHostPath);
this.proxyDocument = proxyDocument;
this.proxyLocation = proxyLocation;
} else { // 非降级模式
const { proxyWindow, proxyDocument, proxyLocation } = proxyGenerator();
this.proxy = proxyWindow;
this.proxyDocument = proxyDocument;
this.proxyLocation = proxyLocation;
}
this.provide.location = this.proxyLocation;
addSandboxCacheWithWujie(this.id, this);
}
}7-2,createWujieWebComponent, renderElementToContainer, renderTemplateToShadowRoot
export function proxyGenerator(
iframe: HTMLIFrameElement,
urlElement: HTMLAnchorElement,
mainHostPath: string,
appHostPath: string
): {
proxyWindow: Window;
proxyDocument: Object;
proxyLocation: Object;
} {
const proxyWindow = new Proxy(iframe.contentWindow, {
get: (target: Window, p: PropertyKey): any => {
// location进行劫持
/*xxx*/
// 修正this指针指向
return getTargetValue(target, p);
},
set: (target: Window, p: PropertyKey, value: any) => {
checkProxyFunction(value);
target = value;
return true;
},
/**其他方法属性**/
});
// proxy document
const proxyDocument = new Proxy(
{},
{
get: function (_fakeDocument, propKey) {
const document = window.document;
const { shadowRoot, proxyLocation } = iframe.contentWindow.__WUJIE;
const rawCreateElement = iframe.contentWindow.__WUJIE_RAW_DOCUMENT_CREATE_ELEMENT__;
const rawCreateTextNode = iframe.contentWindow.__WUJIE_RAW_DOCUMENT_CREATE_TEXT_NODE__;
// need fix
/* 包括元素创建,元素选择操作等
createElement,createTextNode, documentURI,URL,querySelector,querySelectorAll
documentElement,scrollingElement ,forms,images,links等等
*/
// from shadowRoot
if (propKey === "getElementById") {
return new Proxy(shadowRoot.querySelector, {
// case document.querySelector.call
apply(target, ctx, args) {
if (ctx !== iframe.contentDocument) {
return ctx?.apply(ctx, args);
}
return target.call(shadowRoot, `}"]`);
},
});
}
},
}
);
// proxy location
const proxyLocation = new Proxy(
{},
{
get: function (_fakeLocation, propKey) {
const location = iframe.contentWindow.location;
if (
propKey === "host" || propKey === "hostname" || propKey === "protocol" || propKey === "port" ||
propKey === "origin"
) {
return urlElement;
}
/** 拦截相关propKey, 返回对应lication内容
propKey =="href","reload","replace"
**/
return getTargetValue(location, propKey);
},
set: function (_fakeLocation, propKey, value) {
// 如果是跳转链接的话重开一个iframe
if (propKey === "href") {
return locationHrefSet(iframe, value, appHostPath);
}
iframe.contentWindow.location = value;
return true;
}
}
);
return { proxyWindow, proxyDocument, proxyLocation };
}
8 子应用启动执行start
start 开始执行子应用,运行js,执行无界js插件列表
export function localGenerator(
){
// 代理 document
Object.defineProperties(proxyDocument, {
createElement: {
get: () => {
return function (...args) {
const element = rawCreateElement.apply(iframe.contentDocument, args);
patchElementEffect(element, iframe.contentWindow);
return element;
};
},
},
});
// 普通处理
const {
modifyLocalProperties,
modifyProperties,
ownerProperties,
shadowProperties,
shadowMethods,
documentProperties,
documentMethods,
} = documentProxyProperties;
modifyProperties
.filter((key) => !modifyLocalProperties.includes(key))
.concat(ownerProperties, shadowProperties, shadowMethods, documentProperties, documentMethods)
.forEach((key) => {
Object.defineProperty(proxyDocument, key, {
get: () => {
const value = sandbox.document?.;
return isCallable(value) ? value.bind(sandbox.document) : value;
},
});
});
// 代理 location
const proxyLocation = {};
const location = iframe.contentWindow.location;
const locationKeys = Object.keys(location);
const constantKey = ["host", "hostname", "port", "protocol", "port"];
constantKey.forEach((key) => {
proxyLocation = urlElement;
});
Object.defineProperties(proxyLocation, {
href: {
get: () => location.href.replace(mainHostPath, appHostPath),
set: (value) => {
locationHrefSet(iframe, value, appHostPath);
},
},
reload: {
get() {
warn(WUJIE_TIPS_RELOAD_DISABLED);
return () => null;
},
},
});
return { proxyDocument, proxyLocation };
}// getExternalScriptsexport function getExternalScripts(scripts: ScriptObject[],fetch: (input: RequestInfo, init?: RequestInit) => Promise = defaultFetch,loadError: loadErrorHandler,fiber: boolean): ScriptResultList {// module should be requested in iframereturn scripts.map((script) => { const { src, async, defer, module, ignore } = script; let contentPromise = null; // async if ((async || defer) && src && !module) { contentPromise = new Promise((resolve, reject) => fiber ? requestIdleCallback(() => fetchAssets(src, scriptCache, fetch, false, loadError).then(resolve, reject)) : fetchAssets(src, scriptCache, fetch, false, loadError).then(resolve, reject) ); // module || ignore } else if ((module && src) || ignore) { contentPromise = Promise.resolve(""); // inline } else if (!src) { contentPromise = Promise.resolve(script.content); // outline } else { contentPromise = fetchAssets(src, scriptCache, fetch, false, loadError); } return { ...script, contentPromise };});}// 加载assets资源 // 如果存在缓存则从缓存中获取const fetchAssets = (src: string,cache: Object,fetch: (input: RequestInfo, init?: RequestInit) => Promise,cssFlag?: boolean,loadError?: loadErrorHandler) =>cache ||(cache = fetch(src) .then((response) => { /**status > 400按error处理**/ return response.text(); }) }));// insertScriptToIframeexport function insertScriptToIframe(scriptResult: ScriptObject | ScriptObjectLoader,iframeWindow: Window,rawElement?: HTMLScriptElement) {const { src, module, content, crossorigin, crossoriginType, async, callback, onload } = scriptResult as ScriptObjectLoader;const scriptElement = iframeWindow.document.createElement("script");const nextScriptElement = iframeWindow.document.createElement("script");const { replace, plugins, proxyLocation } = iframeWindow.__WUJIE;const jsLoader = getJsLoader({ plugins, replace });let code = jsLoader(content, src, getCurUrl(proxyLocation));// 内联脚本处理if (content) { // patch location if (!iframeWindow.__WUJIE.degrade && !module) { code = `(function(window, self, global, location) { ${code}}).bind(window.__WUJIE.proxy)(window.__WUJIE.proxy,window.__WUJIE.proxy,window.__WUJIE.proxy,window.__WUJIE.proxyLocation,);`; }} else { // 外联自动触发onload onload && (scriptElement.onload = onload as (this: GlobalEventHandlers, ev: Event) => any); src && scriptElement.setAttribute("src", src); crossorigin && scriptElement.setAttribute("crossorigin", crossoriginType);}// esm 模块加载module && scriptElement.setAttribute("type", "module");scriptElement.textContent = code || "";// 执行script队列检测nextScriptElement.textContent = "if(window.__WUJIE.execQueue && window.__WUJIE.execQueue.length){ window.__WUJIE.execQueue.shift()()}";const container = rawDocumentQuerySelector.call(iframeWindow.document, "head");if (/^
页:
[1]