-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMicroFrontend.js
76 lines (66 loc) · 1.8 KB
/
MicroFrontend.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
const MicroFrontend = ({
name,
host,
path,
auth,
history,
handler,
document,
window
}) => {
const renderMicroFrontend = () => {
window[`render${name}`](`${name}-container`, history, handler, auth);
};
const loadScript = (scriptId) => {
fetch(`${host}/${path}/asset-manifest.json`)
.then(res => res.json())
.then(manifest => {
const script = document.createElement('script');
script.id = scriptId;
script.crossOrigin = '';
script.src = `${host}${manifest['files']['main.js']}`;
script.onload = renderMicroFrontend;
document.head.appendChild(script);
});
};
useEffect(() => {
console.log(name, host, path, auth, history, handler);
const scriptId = `micro-frontend-script-${name}`;
if (document.getElementById(scriptId)) {
renderMicroFrontend();
return;
}
loadScript(scriptId);
return function cleanup() {
window[`unmount${name}`](`${name}-container`)
};
}, []);
return (
<main id={`${name}-container`}/>
);
};
MicroFrontend.propTypes = {
name: PropTypes.string.isRequired,
host: PropTypes.string.isRequired,
path: PropTypes.string.isRequired,
auth: PropTypes.shape({
id: PropTypes.string,
token: PropTypes.string
}),
history: PropTypes.any.isRequired,
handler: PropTypes.func,
document: PropTypes.any,
window: PropTypes.any
};
MicroFrontend.defaultProps = {
auth: {
id: null,
token: null
},
handler: () => {},
document,
window,
};
export default MicroFrontend;