-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodule-loader.tsx
More file actions
58 lines (47 loc) · 1.58 KB
/
module-loader.tsx
File metadata and controls
58 lines (47 loc) · 1.58 KB
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
// Credits: Cam Jackson (https://martinfowler.com/articles/micro-frontends.html)
import React, {Component, FunctionComponent} from 'react'
import { ReducersMapObject, Store } from 'redux'
import { ModuleLoaderContext } from './module-loader-context'
import './module-loader.css'
const MOUNT_POINT = 'mount'
type LoaderProps = {
name: string
url: string
}
export const ModuleLoader: FunctionComponent<LoaderProps> = (props) => (
<ModuleLoaderContext.Consumer>
{ value => <LoaderInternal {...props} {...value}/> }
</ModuleLoaderContext.Consumer>
)
type LoaderInternalProps = LoaderProps & {
store: Store,
reducers: ReducersMapObject
}
class LoaderInternal extends Component<LoaderInternalProps> {
componentDidMount(): void {
const { name, url } = this.props
const scriptId = `loader-script-${name}`
if (document.getElementById(scriptId)) {
this.mountModule()
return
}
const script = document.createElement('script')
script.id = scriptId
script.src = url
script.onload = this.mountModule
document.head.appendChild(script)
}
componentWillUnmount() {
const { name } = this.props
const functionName = `unmount${name}`;
(window as any)[functionName](MOUNT_POINT)
}
mountModule = () => {
const { name, store, reducers } = this.props
const functionName = `mount${name}`;
(window as any)[functionName](MOUNT_POINT, store, reducers)
}
render() {
return <div id={MOUNT_POINT} className='ModuleLoader'/>
}
}