This repository has been archived by the owner on May 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
68 lines (55 loc) · 1.97 KB
/
index.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
const { promises: fs } = require('fs');
const path = require('path');
const ora = require('ora');
const chalk = require('chalk');
const { cosmiconfig } = require('cosmiconfig');
const Prerenderer = require('@prerenderer/prerenderer');
const Puppeteer = require('@prerenderer/renderer-puppeteer');
const htmlnano = require('htmlnano');
const prettyMs = require('pretty-ms');
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
module.exports = function prerender(bundler) {
bundler.on('buildEnd', async () => {
if (process.env.NODE_ENV !== 'production') return;
console.log('');
const spinner = ora(chalk.grey('Prerendering')).start();
let routes = ['/']; // the default route
let rendererConfig = {};
const found = await cosmiconfig('prerender').search();
if (found) {
const { config } = found;
if (Array.isArray(config)) {
routes = config;
} else {
if (config.rendererConfig) ({ rendererConfig } = config);
if (config.routes) ({ routes } = config);
}
}
const { outDir } = bundler.options;
const prerenderer = new Prerenderer({
staticDir: outDir,
renderer: new Puppeteer(rendererConfig),
});
await prerenderer.initialize();
const start = Date.now();
const renderedRoutes = await prerenderer.renderRoutes(routes);
await Promise.all(
renderedRoutes.map(async (route) => {
const outputDirectory = path.join(outDir, route.route);
const file = path.resolve(outputDirectory, 'index.html');
await fs.mkdir(outputDirectory, { recursive: true });
const { html } = await htmlnano.process(route.html.trim());
await fs.writeFile(file, html);
}),
);
const end = Date.now();
spinner.stopAndPersist({
symbol: '✨ ',
text: chalk.green(`Prerendered in ${prettyMs(end - start)}.`),
});
prerenderer.destroy();
});
};