-
-
Save fallen90/e96334244ae4ab670d8008af3949a3d2 to your computer and use it in GitHub Desktop.
This file contains 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 from 'react'; | |
class MicroFrontend extends React.Component { | |
componentDidMount() { | |
const { name, host, document } = this.props; | |
const scriptId = `micro-frontend-script-${name}`; | |
if (document.getElementById(scriptId)) { | |
this.renderMicroFrontend(); | |
return; | |
} | |
fetch(`${host}/asset-manifest.json`) | |
.then(res => res.json()) | |
.then(manifest => { | |
const promises = Object.keys(manifest['files']) | |
.filter(key => key.endsWith('.js')) | |
.reduce((sum, key) => { | |
sum.push( | |
new Promise(resolve => { | |
const path = `${host}${manifest['files'][key]}`; | |
const script = document.createElement('script'); | |
if (key === 'main.js') { | |
script.id = scriptId; | |
} | |
script.onload = () => { | |
resolve(); | |
}; | |
script.src = path; | |
document.head.appendChild(script); | |
}) | |
); | |
return sum; | |
}, []); | |
Promise.allSettled(promises).then(() => { | |
renderMicroFrontend(); | |
}); | |
}); | |
} | |
componentWillUnmount() { | |
const { name, window } = this.props; | |
window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`); | |
} | |
renderMicroFrontend = () => { | |
const { name, window, history } = this.props; | |
window[`render${name}`] && | |
window[`render${name}`](`${name}-container`, history); | |
}; | |
render() { | |
return <main id={`${this.props.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