Created
June 25, 2021 12:41
-
-
Save puttpotsawee/feeb901ec2a6c08013395416be089b74 to your computer and use it in GitHub Desktop.
Micro Frontend Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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