微前端技术学习总结

50 阅读1分钟

微前端技术

1、QianKun

底层技术:Single-SPA

1.1、如何加载子应用的代码

通过fetch加载子应用的html文件,然后在用import-html-entry库解析html字符串,提取所有内联/外联的js和css资源。import-html-entry库解析子应用资源时,会自动处理模块依赖关系。

1.2、如何实现JS沙箱隔离

实现JS沙箱隔离有以下几种方法:

1.2.1、通过new Function()
function executeInScope(code) {
  return new Function(`
    (function() {
      const global = {}
      ${code}
    })();
  `);
}
const dynamicJS = 'console.log("执行在闭包内", global);';
executeInScope(dynamicJS)();
1.2.2、通过Proxy

需要注意的是这种方式依赖eval,在内容安全策略(Content Security Policy,CSP)中某些安全策略禁止使用eval关键字。

const globalProxy = new Proxy({ window: {} }, {
  get(target, prop){
    if (prop in target) return target[prop]
  }
})

with(globalProxy) {
  eval('console.log(window)')
}