Skip to content

Commit b48e3a9

Browse files
committed
Chore: Updating html-webpack-plugin to v4 (#1608)
1 parent e19ceb0 commit b48e3a9

File tree

9 files changed

+368
-879
lines changed

9 files changed

+368
-879
lines changed

.changeset/rude-walls-dress.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'preact-cli': minor
3+
'@preact/prerender-data-provider': patch
4+
---
5+
6+
Updates to use html-webpack-plugin v4

packages/cli/lib/lib/webpack/render-html-plugin.js

Lines changed: 63 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
const { resolve, join } = require('path');
22
const os = require('os');
33
const { existsSync, readFileSync, writeFileSync, mkdirSync } = require('fs');
4-
const HtmlWebpackExcludeAssetsPlugin = require('html-webpack-exclude-assets-plugin');
4+
const {
5+
HtmlWebpackSkipAssetsPlugin,
6+
} = require('html-webpack-skip-assets-plugin');
57
const HtmlWebpackPlugin = require('html-webpack-plugin');
68
const prerender = require('./prerender');
79
const createLoadManifest = require('./create-load-manifest');
@@ -16,8 +18,8 @@ function read(path) {
1618
return readFileSync(resolve(__dirname, path), 'utf-8');
1719
}
1820

19-
module.exports = async function (config) {
20-
const { cwd, dest, isProd, src } = config;
21+
module.exports = async function renderHTMLPlugin(config) {
22+
const { cwd, dest, src } = config;
2123
const inProjectTemplatePath = resolve(src, 'template.html');
2224
let template = defaultTemplate;
2325
if (existsSync(inProjectTemplatePath)) {
@@ -33,14 +35,11 @@ module.exports = async function (config) {
3335
}
3436

3537
let content = read(template);
36-
if (/preact\.headEnd|preact\.bodyEnd/.test(content)) {
38+
if (/preact\.(title|headEnd|bodyEnd)/.test(content)) {
3739
const headEnd = read('../../resources/head-end.ejs');
3840
const bodyEnd = read('../../resources/body-end.ejs');
3941
content = content
40-
.replace(
41-
/<%[=]?\s+preact\.title\s+%>/,
42-
'<%= htmlWebpackPlugin.options.title %>'
43-
)
42+
.replace(/<%[=]?\s+preact\.title\s+%>/, '<%= cli.title %>')
4443
.replace(/<%\s+preact\.headEnd\s+%>/, headEnd)
4544
.replace(/<%\s+preact\.bodyEnd\s+%>/, bodyEnd);
4645

@@ -55,53 +54,70 @@ module.exports = async function (config) {
5554
}
5655

5756
const htmlWebpackConfig = values => {
58-
const { url, title, ...routeData } = values;
57+
let { url, title, ...routeData } = values;
58+
59+
title =
60+
title ||
61+
config.title ||
62+
config.manifest.name ||
63+
config.manifest.short_name ||
64+
(config.pkg.name || '').replace(/^@[a-z]\//, '') ||
65+
'Preact App';
66+
5967
// Do not create a folder if the url is for a specific file.
6068
const filename = url.endsWith('.html')
6169
? resolve(dest, url.substring(1))
6270
: resolve(dest, url.substring(1), 'index.html');
63-
return Object.assign(values, {
71+
72+
return {
73+
title,
6474
filename,
6575
template: `!!${require.resolve('ejs-loader')}?esModule=false!${template}`,
66-
minify: isProd && {
67-
collapseWhitespace: true,
68-
removeScriptTypeAttributes: true,
69-
removeRedundantAttributes: true,
70-
removeStyleLinkTypeAttributes: true,
71-
removeComments: true,
76+
templateParameters: (compilation, assets, assetTags, options) => {
77+
let entrypoints = {};
78+
compilation.entrypoints.forEach((entrypoint, name) => {
79+
let entryFiles = entrypoint.getFiles();
80+
entrypoints[name] =
81+
assets.publicPath +
82+
entryFiles.find(file => /\.(m?js)(\?|$)/.test(file));
83+
});
84+
85+
let loadManifest = compilation.assets['push-manifest.json']
86+
? JSON.parse(compilation.assets['push-manifest.json'].source())
87+
: createLoadManifest(
88+
compilation.assets,
89+
config.esm,
90+
compilation.namedChunkGroups
91+
);
92+
93+
return {
94+
cli: {
95+
title,
96+
url,
97+
manifest: config.manifest,
98+
inlineCss: config['inline-css'],
99+
preload: config.preload,
100+
config,
101+
preRenderData: values,
102+
CLI_DATA: { preRenderData: { url, ...routeData } },
103+
ssr: config.prerender ? prerender({ cwd, dest, src }, values) : '',
104+
loadManifest,
105+
entrypoints,
106+
},
107+
htmlWebpackPlugin: {
108+
tags: assetTags,
109+
files: assets,
110+
options,
111+
},
112+
};
72113
},
114+
inject: true,
115+
scriptLoading: 'defer',
73116
favicon: existsSync(resolve(src, 'assets/favicon.ico'))
74117
? 'assets/favicon.ico'
75118
: '',
76-
inject: true,
77-
compile: true,
78-
inlineCss: config['inline-css'],
79-
preload: config.preload,
80-
manifest: config.manifest,
81-
title:
82-
title ||
83-
config.title ||
84-
config.manifest.name ||
85-
config.manifest.short_name ||
86-
(config.pkg.name || '').replace(/^@[a-z]\//, '') ||
87-
'Preact App',
88119
excludeAssets: [/(bundle|polyfills)(\..*)?\.js$/],
89-
createLoadManifest: (assets, namedChunkGroups) => {
90-
if (assets['push-manifest.json']) {
91-
return JSON.parse(assets['push-manifest.json'].source());
92-
}
93-
return createLoadManifest(assets, config.esm, namedChunkGroups);
94-
},
95-
config,
96-
url,
97-
ssr() {
98-
return config.prerender && url !== PREACT_FALLBACK_URL
99-
? prerender({ cwd, dest, src }, values)
100-
: '';
101-
},
102-
scriptLoading: 'defer',
103-
CLI_DATA: { preRenderData: { url, ...routeData } },
104-
});
120+
};
105121
};
106122

107123
let pages = [{ url: '/' }];
@@ -157,7 +173,7 @@ module.exports = async function (config) {
157173
const resultPages = pages
158174
.map(htmlWebpackConfig)
159175
.map(conf => new HtmlWebpackPlugin(conf))
160-
.concat([new HtmlWebpackExcludeAssetsPlugin()]);
176+
.concat([new HtmlWebpackSkipAssetsPlugin()]);
161177

162178
return config.prerender
163179
? resultPages.concat([
@@ -169,10 +185,9 @@ module.exports = async function (config) {
169185
// Adds a preact_prerender_data in every folder so that the data could be fetched separately.
170186
class PrerenderDataExtractPlugin {
171187
constructor(page) {
172-
const cliData = page.CLI_DATA || {};
173-
const { url } = cliData.preRenderData || {};
188+
const url = page.url;
174189
this.location_ = url.endsWith('/') ? url : url + '/';
175-
this.data_ = JSON.stringify(cliData.preRenderData || {});
190+
this.data_ = JSON.stringify(page || {});
176191
}
177192
apply(compiler) {
178193
compiler.hooks.emit.tap('PrerenderDataExtractPlugin', compilation => {

packages/cli/lib/lib/webpack/webpack-client-config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ function isProd(config) {
258258
preload: 'media',
259259
pruneSource: false,
260260
logLevel: 'silent',
261-
additionalStylesheets: ['*.css'],
261+
additionalStylesheets: ['route-*.css'],
262262
})
263263
);
264264
}
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1-
<%= htmlWebpackPlugin.options.ssr() %>
2-
<% if (htmlWebpackPlugin.options.config.prerender === true) { %>
1+
<%= cli.ssr %>
2+
<% if (cli.config.prerender === true) { %>
33
<script type="__PREACT_CLI_DATA__">
4-
<%= encodeURI(JSON.stringify(htmlWebpackPlugin.options.CLI_DATA)) %>
4+
<%= encodeURI(JSON.stringify(cli.CLI_DATA)) %>
55
</script>
66
<% } %>
7-
<% if (webpack.assets.filter(entry => entry.name.match(/bundle(\.\w{5})?.esm.js$/)).length > 0) { %>
8-
<script crossorigin="anonymous" src="<%= htmlWebpackPlugin.files.publicPath %><%= webpack.assets.filter(entry => entry.name.match(/bundle(\.\w{5})?.esm.js$/))[0].name %>" type="module"></script>
7+
<% if (htmlWebpackPlugin.files.js.filter(entry => entry.match(/bundle(\.\w{5})?.esm.js$/)).length > 0) { %>
8+
<script crossorigin="anonymous" src="<%= htmlWebpackPlugin.files.js.filter(entry => entry.match(/bundle(\.\w{5})?.esm.js$/))[0] %>" type="module"></script>
99
<%
1010
/*Fetch and Promise polyfills are not needed for browsers that support type=module
1111
Please re-evaluate below line if adding more polyfills.*/
1212
%>
13-
<script nomodule src="<%= htmlWebpackPlugin.files.chunks["polyfills"].entry %>"></script>
14-
<script nomodule defer src="<%= htmlWebpackPlugin.files.chunks['bundle'].entry %>"></script>
13+
<script nomodule src="<%= cli.entrypoints['polyfills'] %>"></script>
14+
<script nomodule defer src="<%= cli.entrypoints['bundle'] %>"></script>
1515
<% } else { %>
16-
<script <%= htmlWebpackPlugin.options.scriptLoading %> src="<%= htmlWebpackPlugin.files.chunks['bundle'].entry %>"></script>
17-
<script nomodule src="<%= htmlWebpackPlugin.files.chunks["polyfills"].entry %>"></script>
16+
<script <%= htmlWebpackPlugin.options.scriptLoading %> src="<%= cli.entrypoints['bundle'] %>"></script>
17+
<script nomodule src="<%= cli.entrypoints['polyfills'] %>"></script>
1818
<% } %>

packages/cli/lib/resources/head-end.ejs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
<link rel="manifest" href="<%= htmlWebpackPlugin.files.publicPath %>manifest.json">
2-
<% if (htmlWebpackPlugin.options.manifest.theme_color) { %>
3-
<meta name="theme-color" content="<%= htmlWebpackPlugin.options.manifest.theme_color %>">
2+
<% if (cli.manifest.theme_color) { %>
3+
<meta name="theme-color" content="<%= cli.manifest.theme_color %>">
44
<% } %>
5-
<% const loadManifest = htmlWebpackPlugin.options.createLoadManifest(compilation.assets, webpack.namedChunkGroups);%>
6-
<% const filesRegexp = htmlWebpackPlugin.options.inlineCss ? /\.(chunk\.\w{5}\.css|js)$/ : /\.(css|js)$/;%>
7-
<% for (const file in loadManifest[htmlWebpackPlugin.options.url]) { %>
8-
<% if (htmlWebpackPlugin.options.preload && file && file.match(filesRegexp)) { %>
5+
<% const filesRegexp = cli.inlineCss ? /\.(chunk\.\w{5}\.css|js)$/ : /\.(css|js)$/;%>
6+
<% for (const file in cli.loadManifest[cli.url]) { %>
7+
<% if (cli.preload && file && file.match(filesRegexp)) { %>
98
<% /* crossorigin for main bundle as that is loaded from `<script type=module` tag, other lazy loaded bundles are from webpack so its not needed */ %>
109
<link rel="preload" href="<%= htmlWebpackPlugin.files.publicPath + file %>" as="<%= file.match(/\.css$/)?'style':'script' %>" <%= file.match(/bundle\.\w{5}\.esm\.js$/)?'crossorigin="anonymous"':'' %>>
1110
<% } %>

packages/cli/package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494
"compression-webpack-plugin": "^6.0.4",
9595
"console-clear": "^1.0.0",
9696
"copy-webpack-plugin": "^6.2.1",
97-
"critters-webpack-plugin": "^2.5.0",
97+
"critters-webpack-plugin": "^3.0.2",
9898
"cross-spawn-promise": "^0.10.1",
9999
"css-loader": "^5.2.4",
100100
"ejs-loader": "^0.5.0",
@@ -105,8 +105,8 @@
105105
"get-port": "^5.0.0",
106106
"gittar": "^0.1.0",
107107
"glob": "^7.1.4",
108-
"html-webpack-exclude-assets-plugin": "0.0.7",
109-
"html-webpack-plugin": "^3.2.0",
108+
"html-webpack-plugin": "^4.5.2",
109+
"html-webpack-skip-assets-plugin": "1.0.3",
110110
"ip": "^1.1.5",
111111
"isomorphic-unfetch": "^3.1.0",
112112
"kleur": "^4.1.4",

packages/prerender-data-provider/src/hook.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@ function usePrerenderData(props, doAutomaticFetch = true) {
3838
}
3939
}
4040

41-
if (contextValue.CLI_DATA && contextValue.CLI_DATA.preRenderData) {
42-
value = contextValue.CLI_DATA.preRenderData;
41+
if (contextValue) {
42+
value = contextValue;
4343
}
4444

4545
const data = getPrerenderdata(state.value || value, props);

packages/prerender-data-provider/src/render-prop.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ class PreRenderDataSource extends Component {
4949
{contextValue => {
5050
let obtainedContextValue;
5151
// If the data is in script tag, it will be accesible from the following chaining
52-
if (contextValue.CLI_DATA && contextValue.CLI_DATA.preRenderData) {
53-
obtainedContextValue = contextValue.CLI_DATA.preRenderData;
52+
if (contextValue) {
53+
obtainedContextValue = contextValue;
5454
}
5555
const preRenderDataToBePassed = getPrerenderdata(
5656
value || obtainedContextValue,

0 commit comments

Comments
 (0)