Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Created February 23, 2020 02:08
Show Gist options
  • Select an option

  • Save JenniferFuBook/2075e9e67b7c7cccb4c5e03fe2633348 to your computer and use it in GitHub Desktop.

Select an option

Save JenniferFuBook/2075e9e67b7c7cccb4c5e03fe2633348 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 script = document.createElement('script');
script.id = scriptId;
script.crossOrigin = '';
script.src = `${host}${manifest['main.js']}`;
script.onload = this.renderMicroFrontend;
document.head.appendChild(script);
});
}
componentWillUnmount() {
const { name, window } = this.props;
window[`unmount${name}`](`${name}-container`);
}
renderMicroFrontend = () => {
const { name, window, history } = this.props;
window[`render${name}`](`${name}-container`, history);
};
render() {
return <main id={`${this.props.name}-container`} />;
}
}
MicroFrontend.defaultProps = {
document,
window,
};
export default MicroFrontend;
@JenniferFuBook
Copy link
Author

JenniferFuBook commented Feb 23, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment