-
-
Save JenniferFuBook/0cd7d34548c76df1837988692880b54c to your computer and use it in GitHub Desktop.
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; |
A little suggestion: For anybody that using this algorithm and don't want to load all micro front-end JavaScript on the <head>
tag, you can replace the code from line 35 to document.body.after(script)
. It works how expected :)
A little suggestion: For anybody that using this algorithm and don't want to load all micro front-end JavaScript on the
<head>
tag, you can replace the code from line 35 todocument.body.after(script)
. It works how expected :)
Yes, it is a good suggestion. Thanks, @natansevero!
is it possible to pass dynamic props from the host/container app to the microfrontend app?
is it possible to pass dynamic props from the host/container app to the microfrontend app?
We pass an object into the microfrontend app, which includes dynamic props to be used by child components. In turn, the microfrontend app can trigger changes for the container.
Copied and modified from https://github.com/micro-frontends-demo/container/blob/master/src/MicroFrontend.js.