/
index.tsx
143 lines (123 loc) 路 4.96 KB
/
index.tsx
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
import React from 'react'
import { StaticRouter } from 'react-router-dom/server'
import { renderToString } from 'react-dom/server'
import { ChunkExtractor } from '@loadable/server'
import { Provider } from 'react-redux'
import { PreloadedState } from '@reduxjs/toolkit'
import path from 'path'
import compression from 'compression'
import cors from 'cors'
import { HelmetProvider, HelmetServerState } from 'react-helmet-async'
import express, { Request, Response } from 'express'
import { dom } from '@fortawesome/fontawesome-svg-core'
import { JssProvider, SheetsRegistry, createGenerateId, jss } from 'react-jss'
import serialize from 'serialize-javascript'
import { ServerStyleSheet } from 'styled-components'
import postcss from 'postcss'
import autoprefixer from 'autoprefixer'
import { UAParser } from 'ua-parser-js'
import CleanCSS from 'clean-css'
import { ReduxState } from 'store/rootReducer'
import { INITIAL_STATE_MOVIES } from '../store/reducers'
import configureStore from '../store/configureStore'
import App from '../App'
import renderFullPage from './renderFullPage'
import rootSaga from '../store/sagas'
import { paths } from '../../scripts/utils'
import StaticContextProvider from './StaticContext'
const PORT = process.env.PORT || 3000
const app = express()
app.enable('trust proxy')
app.use(cors())
app.use(compression())
if (process.env.NODE_ENV === 'production') {
app.get('/health', (req: Request, res: Response) => {
res.json({ status: 'UP' })
})
}
if (process.env.NODE_ENV === 'development' || (!process.env.STATIC_FILES_URL && process.env.NODE_ENV === 'production')) {
/**
* This middleware is only used in development mode
* In production mode we separate static files from the main Express.js frontend server
* By separating them, you discharge tensions on this Express.js frontend server
* It now depends what kind of router you are using, Nginx my favorite, Traefik. The best
* thing to do is to create a domain alias static, and make a CNAME rediction to it, like
* for example https://static.mywebsite.com/15.bundle-832a294529dcad5060bd.js
* and now the static bundle file 15.bundle-832a294529dcad5060bd.js is served.
*/
app.use(paths.publicPath, express.static(path.join(paths.clientBuild, paths.publicPath)))
}
app.use((req: Request, res: Response) => {
const userAgent = new UAParser(req.headers['user-agent']).getResult()
const acceptedLanguages = Array.isArray(req.acceptsLanguages()) ? req.acceptsLanguages()[0] : req.acceptsLanguages()
const hostname = req.header('host')
let language: string | string[] = 'fr-FR'
const timezone = 'Europe/Paris'
if (acceptedLanguages && acceptedLanguages !== '*') {
language = acceptedLanguages
}
const initialState: Partial<PreloadedState<ReduxState>> = {
app: {
main: {
language,
timezone,
hostname: hostname || null,
userAgent
},
movies: INITIAL_STATE_MOVIES
}
}
const extractor = new ChunkExtractor({
statsFile: path.join(paths.clientBuild, paths.publicPath, 'loadable-stats.json'),
entrypoints: ['bundle']
})
const { store, runSaga, close } = configureStore(initialState)
const sheet = new ServerStyleSheet()
const staticContext = { statusCode: 200 }
const jsx = (helmetContext = { helmet: {} }) => (
<StaticContextProvider staticContext={staticContext}>
<StaticRouter location={req.url}>
<Provider store={store}>
<HelmetProvider context={helmetContext}>
<App />
</HelmetProvider>
</Provider>
</StaticRouter>
</StaticContextProvider>
)
runSaga(rootSaga)
.toPromise()
.then(async () => {
const helmetContext: { helmet: Partial<HelmetServerState> } = { helmet: {} }
const generateId = createGenerateId()
const sheets = new SheetsRegistry()
const html = renderToString(
<JssProvider jss={jss} registry={sheets} generateId={generateId} classNamePrefix="app-">
{sheet.collectStyles(extractor.collectChunks(jsx(helmetContext)))}
</JssProvider>
)
let css = sheets.toString()
const prefixer = postcss([autoprefixer])
const cleanCSS = new CleanCSS()
const prefixerTreated = await prefixer.process(css, { from: undefined })
css = prefixerTreated.css
css = cleanCSS.minify(css).styles
let fontAwesomeCss = dom.css()
fontAwesomeCss = cleanCSS.minify(fontAwesomeCss).styles
const styleTags = sheet.getStyleTags()
const { helmet } = helmetContext
const scriptTags = extractor.getScriptTags()
res
.status(staticContext.statusCode)
.send(renderFullPage(html, css, fontAwesomeCss, styleTags, serialize(store.getState()), helmet, scriptTags))
})
.catch((e: Error) => {
console.log(e.message)
res.status(500).send(e.message)
})
renderToString(jsx())
close()
})
app.listen(PORT, () => {
console.log(`App SSR running ${process.env.NODE_ENV === 'production' ? `port : ${PORT}` : `http://localhost:${PORT}`} 馃寧`)
})