-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (54 loc) · 2.18 KB
/
index.js
File metadata and controls
66 lines (54 loc) · 2.18 KB
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
import React from "react";
import express from "express";
import ReactDOMServer from "react-dom/server";
import App from "../src/App";
import path from "path";
import fs from "fs";
import { StaticRouter } from "react-router-dom";
import { ChunkExtractor } from "@loadable/server";
const app = express();
const port = process.env.port || 8080;
app.get(/\.(js|css|map|ico)$/, express.static("./build"));
app.get("*", (req, res) => {
// This is the stats file generated by webpack loadable plugin.
// It's very important that you use the web stats instead of node stats,
// so use /build/loadable-stats.json instead of /build/server/loadable-stats.json
const statsFile = path.resolve("./build/loadable-stats.json");
// We create an extractor from the statsFile
const extractor = new ChunkExtractor({ statsFile });
// Wrap your application using "collectChunks"
const jsx = extractor.collectChunks(
<StaticRouter location={req.url}>
<App />
</StaticRouter>
);
// Render your application
const html = ReactDOMServer.renderToString(jsx);
// You can also collect your "preload/prefetch" links
const linkTags = extractor.getLinkTags(); // or extractor.getLinkElements();
// console.log(linkTags);
// And you can even collect your style tags (if you use "mini-css-extract-plugin")
const styleTags = extractor.getStyleTags(); // or extractor.getStyleElements();
// console.log(styleTags);
// You can now collect your script tags
const scriptTags = extractor.getScriptTags().replace(/async /g, ""); // or extractor.getScriptElements();
// console.log(scriptTags);
const indexFile = path.resolve("./build/index.html");
fs.readFile(indexFile, "utf8", (err, data) => {
if (err) {
console.error("Something went wrong:", err);
return res.status(500).send("Oops, better luck next time!");
}
return res.send(
data
.replace('<div id="root"></div>', `<div id="root">${html}</div>`)
.replace(
'<script>console.log("loadable tags placeholder")</script>',
`${linkTags}\n${styleTags}\n${scriptTags}`
)
);
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});