-
Notifications
You must be signed in to change notification settings - Fork 27k
/
index.js
246 lines (210 loc) · 7.24 KB
/
index.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom'
import HeadManager from './head-manager'
import { createRouter, makePublicRouterInstance } from 'next/router'
import mitt from 'next-server/dist/lib/mitt'
import { loadGetInitialProps, getURL } from 'next-server/dist/lib/utils'
import PageLoader from './page-loader'
import * as envConfig from 'next-server/config'
import { ErrorBoundary } from './error-boundary'
import Loadable from 'next-server/dist/lib/loadable'
import { HeadManagerContext } from 'next-server/dist/lib/head-manager-context'
import { DataManagerContext } from 'next-server/dist/lib/data-manager-context'
import { RouterContext } from 'next-server/dist/lib/router-context'
import { DataManager } from 'next-server/dist/lib/data-manager'
// Polyfill Promise globally
// This is needed because Webpack's dynamic loading(common chunks) code
// depends on Promise.
// So, we need to polyfill it.
// See: https://webpack.js.org/guides/code-splitting/#dynamic-imports
if (!window.Promise) {
window.Promise = Promise
}
const data = JSON.parse(document.getElementById('__NEXT_DATA__').textContent)
window.__NEXT_DATA__ = data
const {
props,
err,
page,
query,
buildId,
dynamicBuildId,
assetPrefix,
runtimeConfig,
dynamicIds
} = data
const d = JSON.parse(window.__NEXT_DATA__.dataManager)
export const dataManager = new DataManager(d)
const prefix = assetPrefix || ''
// With dynamic assetPrefix it's no longer possible to set assetPrefix at the build time
// So, this is how we do it in the client side at runtime
__webpack_public_path__ = `${prefix}/_next/` //eslint-disable-line
// Initialize next/config with the environment configuration
envConfig.setConfig({
serverRuntimeConfig: {},
publicRuntimeConfig: runtimeConfig
})
const asPath = getURL()
const pageLoader = new PageLoader(buildId, prefix)
const register = ([r, f]) => pageLoader.registerPage(r, f)
if (window.__NEXT_P) {
window.__NEXT_P.map(register)
}
window.__NEXT_P = []
window.__NEXT_P.push = register
const headManager = new HeadManager()
const appContainer = document.getElementById('__next')
let lastAppProps
let webpackHMR
export let router
export let ErrorComponent
let Component
let App
export const emitter = mitt()
export default async ({ webpackHMR: passedWebpackHMR } = {}) => {
// This makes sure this specific lines are removed in production
if (process.env.NODE_ENV === 'development') {
webpackHMR = passedWebpackHMR
}
App = await pageLoader.loadPage('/_app')
let initialErr = err
try {
Component = await pageLoader.loadPage(page)
if (process.env.NODE_ENV !== 'production') {
const { isValidElementType } = require('react-is')
if (!isValidElementType(Component)) {
throw new Error(
`The default export is not a React Component in page: "${page}"`
)
}
}
} catch (error) {
// This catches errors like throwing in the top level of a module
initialErr = error
}
await Loadable.preloadReady(dynamicIds || [])
if (dynamicBuildId === true) {
pageLoader.onDynamicBuildId()
}
router = createRouter(page, query, asPath, {
initialProps: props,
pageLoader,
App,
Component,
err: initialErr
})
router.subscribe(({ App, Component, props, err }) => {
render({ App, Component, props, err, emitter })
})
render({ App, Component, props, err: initialErr, emitter })
return emitter
}
export async function render (props) {
if (props.err) {
await renderError(props)
return
}
try {
await doRender(props)
} catch (err) {
await renderError({ ...props, err })
}
}
// This method handles all runtime and debug errors.
// 404 and 500 errors are special kind of errors
// and they are still handle via the main render method.
export async function renderError (props) {
const { App, err } = props
if (process.env.NODE_ENV !== 'production') {
return webpackHMR.reportRuntimeError(webpackHMR.prepareError(err))
}
// Make sure we log the error to the console, otherwise users can't track down issues.
console.error(err)
ErrorComponent = await pageLoader.loadPage('/_error')
// In production we do a normal render with the `ErrorComponent` as component.
// If we've gotten here upon initial render, we can use the props from the server.
// Otherwise, we need to call `getInitialProps` on `App` before mounting.
const initProps = props.props
? props.props
: await loadGetInitialProps(App, {
Component: ErrorComponent,
router,
ctx: { err, pathname: page, query, asPath }
})
await doRender({ ...props, err, Component: ErrorComponent, props: initProps })
}
let isInitialRender = true
function renderReactElement (reactEl, domEl) {
// The check for `.hydrate` is there to support React alternatives like preact
if (isInitialRender && typeof ReactDOM.hydrate === 'function') {
ReactDOM.hydrate(reactEl, domEl)
isInitialRender = false
} else {
ReactDOM.render(reactEl, domEl)
}
}
async function doRender ({ App, Component, props, err }) {
// Usual getInitialProps fetching is handled in next/router
// this is for when ErrorComponent gets replaced by Component by HMR
if (
!props &&
Component &&
Component !== ErrorComponent &&
lastAppProps.Component === ErrorComponent
) {
const { pathname, query, asPath } = router
props = await loadGetInitialProps(App, {
Component,
router,
ctx: { err, pathname, query, asPath }
})
}
Component = Component || lastAppProps.Component
props = props || lastAppProps.props
const appProps = { Component, err, router, ...props }
// lastAppProps has to be set before ReactDom.render to account for ReactDom throwing an error.
lastAppProps = appProps
emitter.emit('before-reactdom-render', {
Component,
ErrorComponent,
appProps
})
// In development runtime errors are caught by react-error-overlay.
if (process.env.NODE_ENV === 'development') {
renderReactElement(
<Suspense fallback={<div>Loading...</div>}>
<RouterContext.Provider value={makePublicRouterInstance(router)}>
<DataManagerContext.Provider value={dataManager}>
<HeadManagerContext.Provider value={headManager.updateHead}>
<App {...appProps} />
</HeadManagerContext.Provider>
</DataManagerContext.Provider>
</RouterContext.Provider>
</Suspense>,
appContainer
)
} else {
// In production we catch runtime errors using componentDidCatch which will trigger renderError.
renderReactElement(
<ErrorBoundary
fn={error =>
renderError({ App, err: error }).catch(err =>
console.error('Error rendering page: ', err)
)
}
>
<Suspense fallback={<div>Loading...</div>}>
<RouterContext.Provider value={makePublicRouterInstance(router)}>
<DataManagerContext.Provider value={dataManager}>
<HeadManagerContext.Provider value={headManager.updateHead}>
<App {...appProps} />
</HeadManagerContext.Provider>
</DataManagerContext.Provider>
</RouterContext.Provider>
</Suspense>
</ErrorBoundary>,
appContainer
)
}
emitter.emit('after-reactdom-render', { Component, ErrorComponent, appProps })
}