本文介绍微前端运行环境隔离的两套方案。快照沙箱和代理沙箱。其中快照方式有着实现简单易懂、支持低端浏览器的优点,但同时存在耗费内存较多,不支持多个子应用的同时使用的缺点。与之相反,代理隔离相对难理解,并且需要浏览器支持proxy语法,对低端浏览器难以支持。但是对内存的损耗相对较少,同时能够支持多个子应用的同时使用。总的来说,快照沙箱可以是代理沙箱的一种向下兼容方式。废话不多说。我们直接上代码。
快照沙箱
// 快照沙箱
// 应用场景:比较老版本的浏览器,
export class SnapShotSandbox {
constructor() {
// 1. 代理对象
this.proxy = window
this.active()
}
// 沙箱激活
active() {
// 创建一个沙箱快照
this.snapshot = new Map()
// 遍历全局环境
for(const key in window) {
this.snapshot[key] = window[key]
}
}
// 沙箱销毁
inactive () {
for (const key in window) {
if (window[key] !== this.snapshot[key]) {
// 还原操作
window[key] = this.snapshot[key]
}
}
}
}
代理沙箱
// 代理沙箱
let defaultValue = {} // 子应用的沙箱容器
export class ProxySandbox{
constructor() {
this.proxy = null;
this.active()
}
// 沙箱激活
active() {
// 子应用需要设置属性,
this.proxy = new Proxy(window, {
get(target, key) {
if (typeof target[key] === 'function') {
return target[key].bind(target)
}
return defaultValue[key] || target[key]
},
set(target, key, value) {
defaultValue[key] = value
return true
}
})
}
// 沙箱销毁
inactive () {
defaultValue = {}
}
}