-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprerender.ts
More file actions
243 lines (189 loc) · 7.23 KB
/
prerender.ts
File metadata and controls
243 lines (189 loc) · 7.23 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/* eslint-disable no-console */
// Pre-render the app into static HTML.
// run `npm run generate` and then `dist/static` can be served as a static site.
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import crypto from 'node:crypto';
import jsBeautify, { CSSBeautifyOptions, HTMLBeautifyOptions, JSBeautifyOptions } from 'js-beautify';
import * as cheerio from 'cheerio';
import slash from 'slash';
import _ from 'lodash';
import { loadEnv } from 'vite';
import chalk from 'chalk';
export interface PrerenderOptions {
addHash?: boolean;
mode?: string;
}
export const runPrerender = async (options: PrerenderOptions = {}) => {
const mode = options.mode ?? 'production';
const addHash = options.addHash ?? false;
interface RenderedPage {
name: string;
url: string;
fileName: string;
}
const projectRoot = process.cwd();
const xpackEnv = loadEnv(mode, projectRoot);
const toAbsolute = (p: string) => path.resolve(projectRoot, p);
const log = console.log.bind(console);
const template = fs.readFileSync(toAbsolute(process.env.VITE_TEMPLATE ?? 'dist/static/index.html'), 'utf-8');
const { render, routesToPrerender } = await import(pathToFileURL(toAbsolute('./dist/server/entry-server.js')).href);
const beautifyOptions: HTMLBeautifyOptions | JSBeautifyOptions | CSSBeautifyOptions = {
indent_size: 2,
indent_char: ' ',
keep_array_indentation: false,
break_chained_methods: false,
indent_scripts: 'normal',
brace_style: 'collapse',
space_before_conditional: true,
unescape_strings: false,
jslint_happy: false,
end_with_newline: false,
wrap_line_length: 0,
indent_inner_html: false,
comma_first: false,
e4x: false,
indent_empty_lines: false,
wrap_attributes: 'force',
max_preserve_newlines: 5,
preserve_newlines: true,
};
// determine routes to pre-render from src/pages
const updateResourcePath = ($: cheerio.CheerioAPI, tagName: string, attr: string, addHash: boolean) => {
$(tagName).each((_, el) => {
const href = $(el).attr(attr);
if (href && href.startsWith('/')) {
let newPath = href;
if (process.env.VITE_DOMAIN) {
newPath = process.env.VITE_DOMAIN + newPath;
}
if (
href.startsWith(xpackEnv.VITE_BASE_URL) &&
!href.startsWith(xpackEnv.VITE_BASE_URL + 'assets/vendors/') &&
['.css', '.ico', '.js', '.webmanifest', '.svg'].includes(path.extname(href).toLowerCase()) &&
!/\.0x[a-z0-9]{8}\.\w+$/gi.test(href)
) {
const path = toAbsolute('dist/static/' + href.substring(xpackEnv.VITE_BASE_URL.length));
if (fs.existsSync(path)) {
const content = fs.readFileSync(path);
const sha1Hash = crypto.createHash('sha1');
sha1Hash.update(content);
const hash = sha1Hash.digest('base64url').substring(0, 10);
if (addHash) {
newPath += '?v=' + hash;
}
} else if (path.endsWith('mock-api.js')) {
// Skip
} else {
// Log warning
log(chalk.yellow('Cannot find:', path));
}
}
if (newPath != href) {
$(el).attr(attr, newPath);
}
}
});
};
const removeStyleBase = ($: cheerio.CheerioAPI) => {
$('link[rel="stylesheet"]').each((_, el) => {
const href = $(el).attr('href');
if (href?.includes('style-base')) {
$(el).remove();
}
});
};
const removeDuplicateAssets = ($: cheerio.CheerioAPI, selector: string, attr: string, paths: string[]) => {
$(selector).each((_, el) => {
if ($(el).attr('data-pl-inplace') === 'true') {
return;
}
const path = $(el).attr(attr);
if (!path) {
return;
}
const index = $(el).index();
const parent = $(el).parent().clone();
const child = parent.children()[index];
parent.empty();
parent.append(child);
const html = parent.html();
$(el).after('\n<!-- ' + html + ' -->');
if (paths.includes(path)) {
$(el).remove();
return;
}
paths.push(path);
$(el).removeAttr('data-pl-require');
if ($(el).attr('type') === 'module') {
const deferValue = $(el).attr('defer');
if ($(el).attr('defer') === '' || deferValue === 'defer' || deferValue === 'true') {
$(el).removeAttr('defer');
}
}
$('head').append(el);
});
};
const viteAbsoluteUrl = (remain: string, addExtension = false): string => {
const baseUrl = xpackEnv.VITE_BASE_URL;
const normalizedRemain =
(remain?.startsWith('/') ? remain : '/' + remain) + (addExtension && !remain.endsWith('/') ? (xpackEnv.VITE_PATH_EXTENSION ?? '') : '');
if (!baseUrl) {
return normalizedRemain;
}
if (!baseUrl.endsWith('/')) {
return baseUrl + normalizedRemain;
}
const len = baseUrl.length;
return baseUrl.substring(0, len - 1) + normalizedRemain;
};
const renderPage = async (renderedPages: RenderedPage[], addHash: boolean) => {
// pre-render each route...
for (const route of routesToPrerender) {
const output = await render(viteAbsoluteUrl(route.route, true));
const destLocalizedFolderPath = toAbsolute('dist/static');
let html = template.replace('<!--app-html-->', output.html ?? '').replace('@style.scss', '/assets/css/' + route.name + '.css');
const $ = cheerio.load(html);
const paths: string[] = [];
removeDuplicateAssets($, 'link[data-pl-require][href]', 'href', paths);
removeDuplicateAssets($, 'script[data-pl-require][src]', 'src', paths);
updateResourcePath($, 'link', 'href', addHash);
updateResourcePath($, 'script', 'src', addHash);
updateResourcePath($, 'img', 'src', addHash);
if (route.route === '/') {
removeStyleBase($);
}
$('head title').text(route.name);
const fileName = (route.route === '/' ? '/index' : route.route) + '.html';
const filePath = `${destLocalizedFolderPath}${fileName}`;
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
html = $.html();
html = jsBeautify.html_beautify(html, beautifyOptions);
html = html.replace('/* app-styles */', output.styles);
fs.writeFileSync(toAbsolute(filePath), html);
log('pre-rendered:', slash(filePath));
renderedPages.push({
name: _.kebabCase(fileName.replaceAll(/\.\w+$/gi, '')),
url: `${process.env.VITE_DOMAIN ?? ''}${fileName}`,
fileName: fileName,
});
}
};
const renderedPages: RenderedPage[] = [];
const pool: Promise<unknown>[] = [];
pool.push(renderPage(renderedPages, addHash));
await Promise.all(pool);
}; // end runPrerender
// Direct execution support
const isDirectRun = process.argv[1]?.endsWith('prerender.js') || process.argv[1]?.endsWith('prerender.ts');
if (isDirectRun) {
const argvModeIndex = process.argv.indexOf('--mode');
const mode =
argvModeIndex >= 0 && argvModeIndex < process.argv.length - 1 && !process.argv[argvModeIndex + 1].startsWith('-')
? process.argv[argvModeIndex + 1]
: 'production';
runPrerender({ addHash: process.argv.includes('--add-hash'), mode });
}