Skip to content

Instantly share code, notes, and snippets.

@rajgadade
Forked from JenniferFuBook/ChunkedMicroFrontend.js
Created January 28, 2022 04:49
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 rajgadade/b3ab998c42d554876f2b0daed3c6cfde to your computer and use it in GitHub Desktop.
Save rajgadade/b3ab998c42d554876f2b0daed3c6cfde 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment