-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (68 loc) · 2.09 KB
/
server.js
File metadata and controls
76 lines (68 loc) · 2.09 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
67
68
69
70
71
72
73
74
75
76
const path = require("path");
const args = require('yargs').argv;
const webpack = require("webpack");
const express = require("express");
const fs = require("fs");
const { JSDOM } = require("jsdom");
const { Script } = require("vm");
const PORT = args.port || process.env.PORT || 8080;
const app = express();
app.set("view engine", "ejs");
app.set("views", "./src");
app.use(express.static("build"));
let webpackMiddleware;
if (process.env.NODE_ENV !== "production") {
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackConfig = require("./webpack.config")(
{},
{ mode: "development" }
);
const compiler = webpack({ ...webpackConfig, mode: "development" });
webpackMiddleware = webpackDevMiddleware(compiler, {
serverSideRender: true,
publicPath: "/"
});
app.use(webpackMiddleware);
}
app.use((req, res, next) => {
const bundle = getBundle(res);
const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
renderElmApp(bundle.file, fullUrl)
.then(renderedHtml => {
res.render("index", { bundlePath: bundle.path, renderedHtml });
})
.catch(next);
});
const getBundle = res => {
let bundlePath;
let file;
if (process.env.NODE_ENV === "production") {
bundlePath = require("./build/stats.json").assetsByChunkName.main;
file = fs.readFileSync(`./build/${bundlePath}`, "utf8");
} else {
bundlePath = res.locals.webpackStats.toJson().assetsByChunkName.main;
file = webpackMiddleware.fileSystem.readFileSync(
path.join(process.cwd(), "build", bundlePath),
"utf8"
);
}
return { path: bundlePath, file };
};
const renderElmApp = (bundleFile, url) =>
new Promise((resolve, reject) => {
const dom = new JSDOM(`<!DOCTYPE html><html><body></body></html>`, {
url,
runScripts: "outside-only"
});
try {
dom.runVMScript(new Script(bundleFile));
} catch (err) {
reject(err);
}
setTimeout(() => {
resolve(dom.window.document.body.innerHTML);
}, 1);
});
app.listen(PORT, '0.0.0.0', () =>
console.log(`arty listening on port http://localhost:${PORT}`)
);