-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.tsx
67 lines (61 loc) · 2.17 KB
/
server.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
import express from 'express'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Capture } from 'react-loadable'
import { getBundles } from 'react-loadable/webpack'
import { StaticRouter } from 'react-router-dom'
import stats from '../build/react-loadable.json'
import App from './App'
// tslint:disable-next-line:no-var-requires
const assets = require(process.env.RAZZLE_ASSETS_MANIFEST)
const server = express()
server
.disable('x-powered-by')
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.get('/*', (req, res) => {
const context: {url?: any} = {}
const modules = []
const modulePusher = (moduleName) => modules.push(moduleName)
const markup = renderToString(
<Capture report={modulePusher}>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</Capture>
)
if (context.url) {
res.redirect(context.url)
} else {
const bundles = getBundles(stats, modules)
const jsChunks = bundles.filter((bundle) => bundle.file.endsWith('.js'))
const cssChunks = bundles.filter((bundle) => bundle.file.endsWith('.css'))
console.log({ url: req.url, cssChunks, jsChunks, modules, bundles })
res.status(200).send(
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<title>Welcome to Razzle</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
${
assets.client.css
? `<link rel="stylesheet" href="${assets.client.css}"></link>`
: ''
}
${cssChunks.map((chunk) => `<link rel="stylesheet" href="${chunk.publicPath}"></link>`).join('\n')}
${
process.env.NODE_ENV === 'production'
? `<script src="${assets.client.js}" defer></script>`
: `<script src="${assets.client.js}" defer crossorigin></script>`
}
${jsChunks.map((chunk) => `<script src="${chunk.publicPath}"></script>`).join('\n')}
</head>
<body>
<div id="root">${markup}</div>
</body>
</html>`
)
}
})
export default server