-
-
Notifications
You must be signed in to change notification settings - Fork 376
/
render-html-plugin.js
193 lines (178 loc) · 5.73 KB
/
render-html-plugin.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
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
const { resolve, join } = require('path');
const os = require('os');
const { existsSync, readFileSync, writeFileSync, mkdirSync } = require('fs');
const HtmlWebpackExcludeAssetsPlugin = require('html-webpack-exclude-assets-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const prerender = require('./prerender');
const createLoadManifest = require('./create-load-manifest');
const { esmImport, warn } = require('../../util');
const PREACT_FALLBACK_URL = '/200.html';
let defaultTemplate = resolve(__dirname, '../../resources/template.html');
function read(path) {
return readFileSync(resolve(__dirname, path), 'utf-8');
}
module.exports = async function (config) {
const { cwd, dest, isProd, src } = config;
const inProjectTemplatePath = resolve(src, 'template.html');
let template = defaultTemplate;
if (existsSync(inProjectTemplatePath)) {
template = inProjectTemplatePath;
}
if (config.template) {
const templatePathFromArg = resolve(cwd, config.template);
if (existsSync(templatePathFromArg)) template = templatePathFromArg;
else {
warn(`Template not found at ${templatePathFromArg}`);
}
}
let content = read(template);
if (/preact\.headEnd|preact\.bodyEnd/.test(content)) {
const headEnd = read('../../resources/head-end.ejs');
const bodyEnd = read('../../resources/body-end.ejs');
content = content
.replace(
/<%[=]?\s+preact\.title\s+%>/,
'<%= htmlWebpackPlugin.options.title %>'
)
.replace(/<%\s+preact\.headEnd\s+%>/, headEnd)
.replace(/<%\s+preact\.bodyEnd\s+%>/, bodyEnd);
// Unfortunately html-webpack-plugin expects a true file,
// so we'll create a temporary one.
const tmpDir = join(os.tmpdir(), 'preact-cli');
if (!existsSync(tmpDir)) {
mkdirSync(tmpDir);
}
template = resolve(tmpDir, 'template.tmp.ejs');
writeFileSync(template, content);
}
const htmlWebpackConfig = values => {
const { url, title, ...routeData } = values;
// Do not create a folder if the url is for a specific file.
const filename = url.endsWith('.html')
? resolve(dest, url.substring(1))
: resolve(dest, url.substring(1), 'index.html');
return Object.assign(values, {
filename,
template: `!!${require.resolve('ejs-loader')}?esModule=false!${template}`,
minify: isProd && {
collapseWhitespace: true,
removeScriptTypeAttributes: true,
removeRedundantAttributes: true,
removeStyleLinkTypeAttributes: true,
removeComments: true,
},
favicon: existsSync(resolve(src, 'assets/favicon.ico'))
? 'assets/favicon.ico'
: '',
inject: true,
compile: true,
inlineCss: config['inline-css'],
preload: config.preload,
manifest: config.manifest,
title:
title ||
config.title ||
config.manifest.name ||
config.manifest.short_name ||
(config.pkg.name || '').replace(/^@[a-z]\//, '') ||
'Preact App',
excludeAssets: [/(bundle|polyfills)(\..*)?\.js$/],
createLoadManifest: (assets, namedChunkGroups) => {
if (assets['push-manifest.json']) {
return JSON.parse(assets['push-manifest.json'].source());
}
return createLoadManifest(assets, config.esm, namedChunkGroups);
},
config,
url,
ssr() {
return config.prerender && url !== PREACT_FALLBACK_URL
? prerender({ cwd, dest, src }, values)
: '';
},
scriptLoading: 'defer',
CLI_DATA: { preRenderData: { url, ...routeData } },
});
};
let pages = [{ url: '/' }];
if (config.prerenderUrls) {
if (existsSync(resolve(cwd, config.prerenderUrls))) {
try {
let result = esmImport(resolve(cwd, config.prerenderUrls));
if (typeof result.default !== 'undefined') {
result = result.default;
}
if (typeof result === 'function') {
result = await result();
}
if (typeof result === 'string') {
result = JSON.parse(result);
}
if (Array.isArray(result)) {
pages = result;
}
} catch (error) {
warn(
`Failed to load prerenderUrls file, using default!\n${
config.verbose ? error.stack : error.message
}`
);
}
// don't warn if the default file doesn't exist
} else if (
config.prerenderUrls !== 'prerender-urls.json' ||
config.verbose
) {
warn(
`prerenderUrls file (${resolve(
cwd,
config.prerenderUrls
)}) doesn't exist, using default!`
);
}
}
/**
* We cache a non SSRed page in service worker so that there is
* no flash of content when user lands on routes other than `/`.
* And we dont have to cache every single html file.
* Go easy on network usage of clients.
*/
!pages.find(page => page.url === PREACT_FALLBACK_URL) &&
config.sw &&
pages.push({ url: PREACT_FALLBACK_URL });
const resultPages = pages
.map(htmlWebpackConfig)
.map(conf => new HtmlWebpackPlugin(conf))
.concat([new HtmlWebpackExcludeAssetsPlugin()]);
return config.prerender
? resultPages.concat([
...pages.map(page => new PrerenderDataExtractPlugin(page)),
])
: resultPages;
};
// Adds a preact_prerender_data in every folder so that the data could be fetched separately.
class PrerenderDataExtractPlugin {
constructor(page) {
const cliData = page.CLI_DATA || {};
const { url } = cliData.preRenderData || {};
this.location_ = url.endsWith('/') ? url : url + '/';
this.data_ = JSON.stringify(cliData.preRenderData || {});
}
apply(compiler) {
compiler.hooks.emit.tap('PrerenderDataExtractPlugin', compilation => {
if (this.location_ === `${PREACT_FALLBACK_URL}/`) {
// We dont build prerender data for `200.html`. It can re-use the one for homepage.
return;
}
let path = this.location_ + 'preact_prerender_data.json';
if (path.startsWith('/')) {
path = path.substr(1);
}
compilation.assets[path] = {
source: () => this.data_,
size: () => this.data_.length,
};
});
}
}
exports.PREACT_FALLBACK_URL = PREACT_FALLBACK_URL;