Skip to content

Commit cc911d0

Browse files
Prepare Netlify port
1 parent abc6310 commit cc911d0

File tree

4 files changed

+31417
-11227
lines changed

4 files changed

+31417
-11227
lines changed

build.js

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
const Bundler = require("parcel-bundler");
2+
const { execSync } = require("child_process");
3+
const fs = require("fs");
4+
const path = require("path");
5+
const ora = require("ora");
6+
const chalk = require("chalk");
7+
const mkdirp = require("mkdirp");
8+
const Prerenderer = require("@prerenderer/prerenderer");
9+
const Puppeteer = require("@prerenderer/renderer-puppeteer");
10+
const htmlnano = require("htmlnano");
11+
const prettyMs = require("pretty-ms");
12+
13+
const bundler = new Bundler("src/index.html", {
14+
watch: false,
15+
publicUrl: process.env.PUBLIC_URL
16+
});
17+
18+
bundler.on("buildEnd", async () => {
19+
if (process.env.NODE_ENV !== "production") return;
20+
console.log("");
21+
const spinner = ora(chalk.grey("Prerendering")).start();
22+
let routes = ["/"]; // the default route
23+
let rendererConfig = {
24+
renderAfterDocumentEvent: "post-react-render"
25+
};
26+
27+
const { outDir } = bundler.options;
28+
29+
const publicPathOutDir = `${outDir}${process.env.PUBLIC_URL}`;
30+
mkdirp.sync(publicPathOutDir);
31+
execSync(
32+
`find ${outDir} -maxdepth 1 -type f | xargs -I {} cp {} ${publicPathOutDir}`
33+
);
34+
35+
const prerenderer = new Prerenderer({
36+
staticDir: outDir,
37+
renderer: new Puppeteer(rendererConfig)
38+
});
39+
try {
40+
await prerenderer.initialize();
41+
const start = Date.now();
42+
const renderedRoutes = await prerenderer.renderRoutes(routes);
43+
await Promise.all(
44+
renderedRoutes.map(async route => {
45+
const outputDir = path.join(outDir, route.route);
46+
const file = path.resolve(outputDir, "index.html");
47+
mkdirp.sync(outputDir);
48+
const { html } = await htmlnano.process(route.html.trim());
49+
// eslint-disable-next-line no-sync
50+
fs.writeFileSync(file, html);
51+
})
52+
);
53+
execSync(`rm -rf ${publicPathOutDir}`);
54+
const end = Date.now();
55+
spinner.stopAndPersist({
56+
symbol: "✨ ",
57+
text: chalk.green(`Prerendered in ${prettyMs(end - start)}.`)
58+
});
59+
} catch (error) {
60+
console.error(error);
61+
// eslint-disable-next-line unicorn/no-process-exit, no-process-exit
62+
process.exit(1);
63+
} finally {
64+
prerenderer.destroy();
65+
}
66+
});
67+
68+
bundler.bundle();

0 commit comments

Comments
 (0)