asma-qiankun-plugin-vite
Version:
vite for qiankun with some adjustments for hmr
104 lines (103 loc) • 3.35 kB
JavaScript
import { load as w } from "cheerio";
const y = (t) => `
const createDeffer = (hookName) => {
const d = new Promise((resolve, reject) => {
window.proxy && (window.proxy[\`vite\${hookName}\`] = resolve)
})
return props => d.then(fn => fn(props));
}
const bootstrap = createDeffer('bootstrap');
const mount = createDeffer('mount');
const unmount = createDeffer('unmount');
const update = createDeffer('update');
;(global => {
global.qiankunName = '${t}';
global['${t}'] = {
bootstrap,
mount,
unmount,
update
};
})(window);
`, h = (t) => `
const global_concurrent_qiankun = window.proxy?.__GLOBAL_CONCURRENT_QIANKUN__?.['${t}']
if(global_concurrent_qiankun){
window.proxy = global_concurrent_qiankun
}
const qiankunLifeCycle = window.moduleQiankunAppLifeCycles && window.moduleQiankunAppLifeCycles['${t}'];
if (qiankunLifeCycle) {
window.proxy.vitemount((props) => qiankunLifeCycle.mount(props));
window.proxy.viteunmount((props) => qiankunLifeCycle.unmount(props));
window.proxy.vitebootstrap(() => qiankunLifeCycle.bootstrap());
window.proxy.viteupdate((props) => qiankunLifeCycle.update(props));
}
`, b = (t, i) => `import((window.proxy ? (window.proxy?.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ + '..') : '') + '${t}').then(${i})`, v = (t) => `
let RefreshRuntime;
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
${b(
"/@react-refresh",
`(module) => {
RefreshRuntime=module.default
RefreshRuntime.injectIntoGlobalHook(window)
${t}
}
`
)}`, R = (t, i = {}) => {
let s, a = "";
const d = (e) => {
if (!e.length)
return;
const n = e.attr("src");
if (!n)
return e;
let o = "";
return i.useDevMode && !s && (o = "(window.proxy ? (window.proxy?.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ + '..') : '') + "), e.removeAttr("src"), e.removeAttr("type"), e.html(`import(${o}'${n}')`), e;
};
return {
name: "qiankun-html-transform",
configResolved(e) {
s = e.command === "build" || e.isProduction, a = e.base;
},
configureServer(e) {
return () => {
e.middlewares.use((n, o, p) => {
if (s || !i.useDevMode) {
p();
return;
}
const m = o.end.bind(o);
o.end = (...u) => {
let [r] = u;
const [l, ..._] = u;
if (typeof r == "string") {
const c = w(r);
d(c(`script[src=${a}@vite/client]`)), c("script[type=module]").removeAttr("type").empty();
const f = c("#entry");
f.html(v(f.html())), r = c.html();
}
return m(r, ..._);
}, p();
});
};
},
transformIndexHtml(e) {
const n = w(e), o = n(
'body script[type=module], head script[crossorigin=""]'
);
if (!o || !o.length)
return;
const p = o.length;
return o.each((u, r) => {
const l = d(n(r));
p - 1 === u && l?.html(`${l.html()}.finally(() => {
${h(t)}
})`);
}), n("body").append(`<script>${y(t)}<\/script>`), n.html();
}
};
};
export {
R as qiankun
};