一、微前端环境变量设置
在子应用改造中,已经针对微前端的环境变量做了相应的设置,只是暂未使用。
新建
main/micro/sandbox/index.js
javascriptimport { performScriptForEval } from './performScript' /** * 检测生命周期 * @param lifeCycle */ const isCheckLifeCycle = lifeCycle => lifeCycle && lifeCycle.bootstrap && lifeCycle.mount && lifeCycle.unmount /** * 子应用的生命周期处理和环境变量设置 */ export const sandBox = (app, script) => { // 1. 设置环境变量 window.__MICRO_FRONTEND__ = true // 2. 运行 js 文件 const lifeCycle = performScriptForEval(script, app.name) // 生命周期,挂载到 app 上 if (isCheckLifeCycle(lifeCycle)) { app.bootstrap = lifeCycle.bootstrap app.mount = lifeCycle.mount app.unmount = lifeCycle.unmount } }
改造
main/micro/sandbox/performScript.js
中的 js 执行方法javascript/** * 执行js脚本 * @param script */ export const performScriptForFunction = (script, appName) => { const scriptText = `${script} return window['${appName}'] ` return new Function(scriptText).call(window, window) } export const performScriptForEval = (script, appName) => { const scriptText = `() => { ${script} return window['${appName}'] }` return eval(scriptText).call(window, window) }
在
main/micro/loader/index.js
中调用javascriptimport { sandBox } from '../sandbox' /** * 加载html方法 */ export const loadHtml = async (app) => { window.__MICRO_FRONTEND__ = true // 1. 子应用需要显示在哪里 const container = app.container // 2. 子应用的入口 const entry = app.entry const [dom, scripts] = await parseHtml(entry) const ct = document.querySelector(container) if (!ct) { throw new Error('容器不存在,请查看') } ct.innerHTML = dom scripts.forEach(item => { sandBox(app, item) }) return app }