Skip to content

Instantly share code, notes, and snippets.

@rehrumesh
Created July 5, 2020 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rehrumesh/3cc49dc3033ca0f6a3b2de313abcc69e to your computer and use it in GitHub Desktop.
Save rehrumesh/3cc49dc3033ca0f6a3b2de313abcc69e to your computer and use it in GitHub Desktop.
import React, { useEffect } from "react";
function MicroFrontend({ name, host, history }) {
useEffect(() => {
const scriptId = `micro-frontend-script-${name}`;
const renderMicroFrontend = () => {
window[`render${name}`](`${name}-container`, history);
};
if (document.getElementById(scriptId)) {
renderMicroFrontend();
return;
}
fetch(`${host}/asset-manifest.json`)
.then((res) => res.json())
.then((manifest) => {
const script = document.createElement("script");
script.id = scriptId;
script.crossOrigin = "";
script.src = `${host}${manifest.files["main.js"]}`;
script.onload = () => {
renderMicroFrontend();
};
document.head.appendChild(script);
});
return () => {
window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`);
};
});
return <main id={`${name}-container`} />;
}
MicroFrontend.defaultProps = {
document,
window,
};
export default MicroFrontend;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment