Repository URL to install this package:
|
Version:
1.3.2 ▾
|
import React from 'react'
import { ComponentType } from 'react'
import { LoadableContext } from './LoadableContext'
import { AsyncRequire } from './typings'
function loadable<Type = ComponentType>(asyncRequire: AsyncRequire<Type>) {
const scoped = new LoadableContext<Type>(asyncRequire)
if (typeof window !== 'object') {
scoped.init()
}
/**
* @todo could simply scope this
* & pass in the loading as a prop for better @@perf?
*/
return class Component extends React.PureComponent<any> {
static debugName = 'CodeSplit'
componentWillMount() {
if (scoped.isLoaded === false) {
const onLoad = () => {
console.debug('[code-splitting] onLoad: ', scoped.componentName)
this.forceUpdate()
}
scoped.wait().then(onLoad)
}
}
render() {
console.debug('[code-splitting] render')
if (scoped.isLoaded === false) {
return 'loading'
} else if (!scoped.resolved) {
console.log(this)
return 'error!'
} else {
return React.createElement(scoped.resolved as any, this.props)
}
}
}
}
export { loadable }
export default loadable