-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
70 lines (63 loc) · 2.17 KB
/
server.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
import express from 'express'
import path from 'path'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import {Capture, preloadAll} from '@react-loadable/revised'
import {getBundles} from '@react-loadable/revised/lib'
import App from './components/App'
import fs from 'fs'
const getStats = () => JSON.parse(fs.readFileSync(path.resolve(__dirname, 'dist/react-loadable.json'), 'utf8'))
const app = express()
const Links = ({assets, prefetch}) => {
const urls = assets.filter(file => file.endsWith('.css'))
return prefetch
? urls.map((url, index) => <link rel={prefetch} as="style" href={url} key={index}/>)
: urls.map((url, index) => <link rel="stylesheet" href={url} key={index}/>)
}
const Scripts = ({assets, prefetch}) => {
const urls = assets.filter(file => file.endsWith('.js') )
return prefetch
? urls.map((url, index) => <link rel={prefetch} as="script" href={url} key={index}/>)
: urls.map((url, index) => <script src={url} key={index}/>)
}
const Html = ({assets, body, preload, prefetch}) => {
return <html lang="en">
<head>
<meta charSet="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta httpEquiv="X-UA-Compatible" content="ie=edge"/>
<title>My App</title>
<Links assets={assets}/>
<Links assets={preload} prefetch="preload"/>
<Links assets={prefetch} prefetch="prefetch"/>
<Scripts assets={preload} prefetch="preload"/>
<Scripts assets={prefetch} prefetch="prefetch"/>
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{__html: body}}/>
<Scripts assets={assets}/>
</body>
</html>
}
app.get('/', (req, res) => {
const modules = []
const body = ReactDOMServer.renderToString(
<Capture report={moduleName => modules.push(moduleName)}>
<App/>
</Capture>
)
const {assets, preload, prefetch} = getBundles(getStats(), modules)
res.send(`<!doctype html>
${ReactDOMServer.renderToStaticMarkup(<Html
assets={assets}
body={body}
preload={preload}
prefetch={prefetch}
/>)}`)
})
app.use('/dist', express.static(path.join(__dirname, 'dist', 'client')))
preloadAll().then(() => {
app.listen(3000, () => {
console.log('Running on http://localhost:3000/')
})
}).catch(console.error)