Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Last active July 4, 2023 00:38
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JenniferFuBook/0cd7d34548c76df1837988692880b54c to your computer and use it in GitHub Desktop.
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;
@JenniferFuBook
Copy link
Author

@natansevero
Copy link

natansevero commented Jun 22, 2020

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 :)

@JenniferFuBook
Copy link
Author

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 :)

Yes, it is a good suggestion. Thanks, @natansevero!

@cheejiayuan512
Copy link

is it possible to pass dynamic props from the host/container app to the microfrontend app?

@JenniferFuBook
Copy link
Author

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.

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