-
Notifications
You must be signed in to change notification settings - Fork 2
/
prerender.js
84 lines (73 loc) · 2.36 KB
/
prerender.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const fs = require("fs");
const path = require("path");
const mkdirp = require("mkdirp");
const Prerenderer = require("@prerenderer/prerenderer");
const JSDOMRenderer = require("@prerenderer/renderer-jsdom");
const routes = [
"/404",
"/cases/by-postcode",
"/cases/by-council",
"/vaccines/by-postcode",
"/vaccines/by-council",
"/about",
// Old routes for compat reasons
"/",
"/postcodes",
"/postcodes/vaccinations",
"/councils",
"/councils/vaccinations",
];
const staticDir = path.join(__dirname, "dist");
const prerenderer = new Prerenderer({
// Required - The path to the app to prerender. Should have an index.html and any other needed assets.
staticDir,
// The plugin that actually renders the page.
renderer: new JSDOMRenderer({
renderAfterDocumentEvent: "x-render-trigger",
}),
});
// Initialize is separate from the constructor for flexibility of integration with build systems.
prerenderer
.initialize()
.then(() => {
console.time("renderRoutes");
// List of routes to render.
return prerenderer.renderRoutes(routes);
})
.then((renderedRoutes) => {
console.timeEnd("renderRoutes");
renderedRoutes.forEach(async (renderedRoute) => {
const { route, html } = postProcess(renderedRoute);
const outputPath = path.join(
staticDir,
route === "/" ? "index.html" : route + ".html"
);
console.log(outputPath);
// console.log(html);
await mkdirp(path.dirname(outputPath));
fs.writeFile(outputPath, html.trim(), () => {});
});
// Shut down the file server and renderer.
prerenderer.destroy();
})
.catch((err) => {
// Shut down the server and renderer.
prerenderer.destroy();
// Handle errors.
console.error(err);
});
function postProcess(renderedRoute) {
// Ignore any redirects.
renderedRoute.route = renderedRoute.originalRoute;
renderedRoute.html = renderedRoute.html
// Remove <noscript> tag for prerendered pages as they work without JS
.replace(/<noscript>.+?<\/noscript>/g, "")
// Remove gtag stuff so it doesn't get added twice
.replace(
`<link href="https://www.googletagmanager.com" rel="preconnect"><script src="https://www.googletagmanager.com/gtag/js?id=UA-103555680-12&l=dataLayer"></script>`,
""
)
// Remove empty class attributes
.replace(/ class=""/g, "");
return renderedRoute;
}