-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
40 lines (33 loc) · 974 Bytes
/
Copy pathserver.js
File metadata and controls
40 lines (33 loc) · 974 Bytes
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
import express from 'express';
import React from 'react';
import { ServerStyleSheet } from 'styled-components';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import path from 'path';
import fs from 'fs';
import App from './src/App';
const app = express();
app.use(express.static('./build', { index: false }))
app.get('/*', (req, res) => {
const sheet = new ServerStyleSheet();
const reactApp = renderToString(
sheet.collectStyles(
<StaticRouter location={req.url}>
<App />
</StaticRouter>
)
);
const templateFile = path.resolve('./build/index.html');
fs.readFile(templateFile, 'utf8', (err, data) => {
if (err) {
return res.status(500).send(err);
}
return res.send(
data.replace('<div id="root"></div>', `<div id="root">${reactApp}</div>`)
.replace('{{ styles }}', sheet.getStyleTags())
)
});
});
app.listen(8080, () => {
console.log('Server is listening on port 8080');
});