-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathasyncComponent.js
205 lines (182 loc) · 5.43 KB
/
asyncComponent.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import React from 'react'
import PropTypes from 'prop-types'
const validSSRModes = ['resolve', 'defer', 'boundary']
export default function asyncComponent(config) {
const {
name,
resolve,
autoResolveES2015Default = true,
serverMode = 'resolve',
LoadingComponent,
ErrorComponent,
} = config
if (validSSRModes.indexOf(serverMode) === -1) {
throw new Error('Invalid serverMode provided to asyncComponent')
}
const env =
['node', 'browser'].indexOf(config.env) > -1
? config.env
: typeof window === 'undefined'
? 'node'
: 'browser'
const state = {
// A unique id we will assign to our async component which is especially
// useful when rehydrating server side rendered async components.
id: null,
// This will be use to hold the resolved module allowing sharing across
// instances.
// NOTE: When using React Hot Loader this reference will become null.
module: null,
// If an error occurred during a resolution it will be stored here.
error: null,
// Allows us to share the resolver promise across instances.
resolver: null,
// Indicates whether resolving is taking place
resolving: false,
// Handle on the contexts so we don't lose it during async resolution
asyncComponents: null,
asyncComponentsAncestor: null,
}
const needToResolveOnBrowser = () =>
state.module == null &&
state.error == null &&
!state.resolving &&
typeof window !== 'undefined'
// Takes the given module and if it has a ".default" the ".default" will
// be returned. i.e. handy when you could be dealing with es6 imports.
const es6Resolve = x =>
autoResolveES2015Default &&
x != null &&
(typeof x === 'function' || typeof x === 'object') &&
x.default
? x.default
: x
const getResolver = () => {
if (state.resolver == null) {
state.resolving = true
try {
state.resolver = Promise.resolve(resolve())
} catch (err) {
state.resolver = Promise.reject(err)
}
}
return state.resolver
}
return class AsyncComponent extends React.Component {
static displayName = name || 'AsyncComponent'
static contextTypes = {
asyncComponentsAncestor: PropTypes.shape({
isBoundary: PropTypes.bool,
}),
asyncComponents: PropTypes.shape({
getNextId: PropTypes.func.isRequired,
resolved: PropTypes.func.isRequired,
shouldRehydrate: PropTypes.func.isRequired,
}),
}
static childContextTypes = {
asyncComponentsAncestor: PropTypes.shape({
isBoundary: PropTypes.bool,
}),
}
getChildContext() {
return {
asyncComponentsAncestor:
state.asyncComponents == null
? null
: {
isBoundary: serverMode === 'boundary',
},
}
}
componentWillMount() {
if (this.context.asyncComponents != null) {
state.asyncComponents = this.context.asyncComponents
state.asyncComponentsAncestor = this.context.asyncComponentsAncestor
if (!state.id) {
state.id = this.context.asyncComponents.getNextId()
}
}
}
// react-async-bootstrapper
bootstrap() {
const doResolve = () =>
this.resolveModule().then(
module => (module === undefined ? false : undefined),
)
// browser
if (env === 'browser') {
const { shouldRehydrate, getError } = state.asyncComponents
const error = getError(state.id)
if (error) {
state.error = error
return false
}
return shouldRehydrate(state.id) ? doResolve() : false
}
// node
const isChildOfBoundary =
state.asyncComponentsAncestor != null &&
state.asyncComponentsAncestor.isBoundary
return serverMode === 'defer' || isChildOfBoundary ? false : doResolve()
}
componentDidMount() {
if (needToResolveOnBrowser()) {
this.resolveModule()
}
}
resolveModule() {
return getResolver()
.then(module => {
if (state.asyncComponents != null) {
state.asyncComponents.resolved(state.id)
}
state.module = module
state.error = null
state.resolving = false
return module
})
.catch(({ message, stack }) => {
const error = { message, stack }
if (state.asyncComponents != null) {
state.asyncComponents.failed(state.id, error)
}
state.error = error
state.resolving = false
if (!ErrorComponent) {
// eslint-disable-next-line no-console
console.error(error)
}
})
.then(result => {
if (this.unmounted) {
return undefined
}
if (
!this.context.reactAsyncBootstrapperRunning &&
env === 'browser'
) {
this.forceUpdate()
}
return result
})
}
componentWillUnmount() {
this.unmounted = true
}
render() {
const { module, error } = state
if (error) {
return ErrorComponent ? (
<ErrorComponent {...this.props} error={error} />
) : null
}
const Component = es6Resolve(module)
return Component ? (
<Component {...this.props} />
) : LoadingComponent ? (
<LoadingComponent {...this.props} />
) : null
}
}
}