Skip to content

Commit

Permalink
update html-webpack-plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
ForsakenHarmony committed Oct 31, 2020
1 parent 5bc19d1 commit 754c3a2
Show file tree
Hide file tree
Showing 8 changed files with 228 additions and 190 deletions.
113 changes: 66 additions & 47 deletions packages/cli/lib/lib/webpack/render-html-plugin.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
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 {
HtmlWebpackSkipAssetsPlugin,
} = require('html-webpack-skip-assets-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const prerender = require('./prerender');
const createLoadManifest = require('./create-load-manifest');
Expand All @@ -15,8 +17,8 @@ function read(path) {
return readFileSync(resolve(__dirname, path), 'utf-8');
}

module.exports = async function (config) {
const { cwd, dest, isProd, src } = config;
module.exports = async function renderHTMLPlugin(config) {
const { cwd, dest, src } = config;
const inProjectTemplatePath = resolve(src, 'template.html');
let template = defaultTemplate;
if (existsSync(inProjectTemplatePath)) {
Expand All @@ -25,8 +27,9 @@ module.exports = async function (config) {

if (config.template) {
const templatePathFromArg = resolve(cwd, config.template);
if (existsSync(templatePathFromArg)) template = templatePathFromArg;
else {
if (existsSync(templatePathFromArg)) {
template = templatePathFromArg;
} else {
warn(`Template not found at ${templatePathFromArg}`);
}
}
Expand All @@ -36,10 +39,7 @@ module.exports = async function (config) {
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\.title\s+%>/, '<%= cli.title %>')
.replace(/<%\s+preact\.headEnd\s+%>/, headEnd)
.replace(/<%\s+preact\.bodyEnd\s+%>/, bodyEnd);

Expand All @@ -54,47 +54,66 @@ module.exports = async function (config) {
}

const htmlWebpackConfig = values => {
const { url, title, ...routeData } = values;
return Object.assign(values, {
let { url, title, ...routeData } = values;

title =
title ||
config.title ||
config.manifest.name ||
config.manifest.short_name ||
(config.pkg.name || '').replace(/^@[a-z]\//, '') ||
'Preact App';

return {
title,
filename: resolve(dest, url.substring(1), 'index.html'),
template: `!!ejs-loader?esModule=false!${template}`,
minify: isProd && {
collapseWhitespace: true,
removeScriptTypeAttributes: true,
removeRedundantAttributes: true,
removeStyleLinkTypeAttributes: true,
removeComments: true,
templateParameters: (compilation, assets, assetTags, options) => {
let entrypoints = {};
compilation.entrypoints.forEach((entrypoint, name) => {
let entryFiles = entrypoint.getFiles();
entrypoints[name] =
assets.publicPath +
entryFiles.find(file => /\.(m?js)(\?|$)/.test(file));
});

let loadManifest = compilation.assets['push-manifest.json']
? JSON.parse(compilation.assets['push-manifest.json'].source())
: createLoadManifest(
compilation.assets,
config.esm,
compilation.namedChunkGroups
);

return {
cli: {
title,
url,
manifest: config.manifest,
inlineCss: config['inline-css'],
preload: config.preload,
config,
preRenderData: values,
CLI_DATA: { preRenderData: { url, ...routeData } },
ssr: config.prerender ? prerender({ cwd, dest, src }, values) : '',
loadManifest,
entrypoints,
},
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options: options,
},
};
},
inject: true,
scriptLoading: 'defer',
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 ? prerender({ cwd, dest, src }, values) : '';
},
scriptLoading: 'defer',
CLI_DATA: { preRenderData: { url, ...routeData } },
});
// excludeChunks: ['bundle', 'polyfills'],
};
};

let pages = [{ url: '/' }];
Expand Down Expand Up @@ -141,18 +160,18 @@ module.exports = async function (config) {
return pages
.map(htmlWebpackConfig)
.map(conf => new HtmlWebpackPlugin(conf))
.concat([new HtmlWebpackExcludeAssetsPlugin()])
.concat([new HtmlWebpackSkipAssetsPlugin()])
.concat([...pages.map(page => new PrerenderDataExtractPlugin(page))]);
};

// 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 || {};
const url = page.url;
this.location_ = url.endsWith('/') ? url : url + '/';
this.data_ = JSON.stringify(cliData.preRenderData || {});
this.data_ = JSON.stringify(page || {});
}

apply(compiler) {
compiler.hooks.emit.tap('PrerenderDataExtractPlugin', compilation => {
let path = this.location_ + PRERENDER_DATA_FILE_NAME;
Expand Down
16 changes: 8 additions & 8 deletions packages/cli/lib/resources/body-end.ejs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
<%= htmlWebpackPlugin.options.ssr() %>
<%= cli.ssr %>
<script type="__PREACT_CLI_DATA__">
<%= encodeURI(JSON.stringify(htmlWebpackPlugin.options.CLI_DATA)) %>
<%= encodeURI(JSON.stringify(cli.CLI_DATA)) %>
</script>
<% if (webpack.assets.filter(entry => entry.name.match(/bundle(\.\w{5})?.esm.js$/)).length > 0) { %>
<% if (htmlWebpackPlugin.files.js.filter(entry => entry.match(/bundle(\.\w{5})?.esm.js$/)).length > 0) { %>
<% /* Fix for safari < 11 nomodule bug. TODO: Do the following only for safari. */ %>
<script nomodule>!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();</script>
<script crossorigin="anonymous" src="<%= htmlWebpackPlugin.files.publicPath %><%= webpack.assets.filter(entry => entry.name.match(/bundle(\.\w{5})?.esm.js$/))[0].name %>" type="module"></script>
<script crossorigin="anonymous" src="<%= htmlWebpackPlugin.files.js.filter(entry => entry.match(/bundle(\.\w{5})?.esm.js$/))[0] %>" type="module"></script>
<%
/*Fetch and Promise polyfills are not needed for browsers that support type=module
Please re-evaluate below line if adding more polyfills.*/
%>
<script nomodule src="<%= htmlWebpackPlugin.files.chunks["polyfills"].entry %>"></script>
<script nomodule defer src="<%= htmlWebpackPlugin.files.chunks['bundle'].entry %>"></script>
<script nomodule src="<%= cli.entrypoints['polyfills'] %>"></script>
<script nomodule defer src="<%= cli.entrypoints['bundle'] %>"></script>
<% } else { %>
<script <%= htmlWebpackPlugin.options.scriptLoading %> src="<%= htmlWebpackPlugin.files.chunks['bundle'].entry %>"></script>
<script nomodule src="<%= htmlWebpackPlugin.files.chunks["polyfills"].entry %>"></script>
<script <%= htmlWebpackPlugin.options.scriptLoading %> src="<%= cli.entrypoints['bundle'] %>"></script>
<script nomodule src="<%= cli.entrypoints['polyfills'] %>"></script>
<% } %>
11 changes: 5 additions & 6 deletions packages/cli/lib/resources/head-end.ejs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
<link rel="manifest" href="<%= htmlWebpackPlugin.files.publicPath %>manifest.json">
<% if (htmlWebpackPlugin.options.manifest.theme_color) { %>
<meta name="theme-color" content="<%= htmlWebpackPlugin.options.manifest.theme_color %>">
<% if (cli.manifest.theme_color) { %>
<meta name="theme-color" content="<%= cli.manifest.theme_color %>">
<% } %>
<% const loadManifest = htmlWebpackPlugin.options.createLoadManifest(compilation.assets, webpack.namedChunkGroups);%>
<% const filesRegexp = htmlWebpackPlugin.options.inlineCss ? /\.(chunk\.\w{5}\.css|js)$/ : /\.(css|js)$/;%>
<% for (const file in loadManifest[htmlWebpackPlugin.options.url]) { %>
<% if (htmlWebpackPlugin.options.preload && file && file.match(filesRegexp)) { %>
<% const filesRegexp = cli.inlineCss ? /\.(chunk\.\w{5}\.css|js)$/ : /\.(css|js)$/;%>
<% for (const file in cli.loadManifest[cli.url]) { %>
<% if (cli.preload && file && file.match(filesRegexp)) { %>
<% /* crossorigin for main bundle as that is loaded from `<script type=module` tag, other lazy loaded bundles are from webpack so its not needed */ %>
<link rel="preload" href="<%= htmlWebpackPlugin.files.publicPath + file %>" as="<%= file.match(/\.css$/)?'style':'script' %>" <%= file.match(/bundle\.\w{5}\.esm\.js$/)?'crossorigin="anonymous"':'' %>>
<% } %>
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@
"get-port": "^5.0.0",
"gittar": "^0.1.0",
"glob": "^7.1.4",
"html-webpack-exclude-assets-plugin": "0.0.7",
"html-webpack-plugin": "^3.2.0",
"html-webpack-skip-assets-plugin": "^0.0.2",
"html-webpack-plugin": "^4.5.0",
"ip": "^1.1.5",
"isomorphic-unfetch": "^3.0.0",
"kleur": "^4.0.2",
Expand Down
20 changes: 10 additions & 10 deletions packages/cli/tests/build.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { join } = require('path');
const { readFile } = require('../lib/fs');
const looksLike = require('html-looks-like');
const { create, build } = require('./lib/cli');
const { snapshot, hasKey, isWithin } = require('./lib/utils');
const { snapshot } = require('./lib/utils');
const { existsSync } = require('fs');
const { subject } = require('./lib/output');
const images = require('./images/build');
Expand Down Expand Up @@ -39,13 +39,13 @@ function getRegExpFromMarkup(markup) {
return new RegExp(minifiedMarkup);
}

function testMatch(src, tar) {
let k, tmp;
let keys = Object.keys(tar);
expect(keys).toHaveLength(Object.keys(src).length);
for (k in src) {
expect(hasKey(k, keys)).toBeTruthy();
if (!isWithin(src[k], tar[tmp])) return false;
function testMatch(expected, received) {
let expectedKeys = Object.keys(expected);
let receivedKeys = Object.keys(received);
expect(receivedKeys).toHaveLength(expectedKeys.length);
for (let k in expected) {
expect(receivedKeys).toContain(k);
expect(received[k]).toBeCloseTo(expected[k]);
}
}

Expand All @@ -58,7 +58,7 @@ describe('preact build', () => {
dir = join(dir, 'build');

let output = await snapshot(dir);
testMatch(output, images[key]);
testMatch(images[key], output);
});

it(`builds the '${key}' output with esm`, async () => {
Expand All @@ -68,7 +68,7 @@ describe('preact build', () => {
dir = join(dir, 'build');

let output = await snapshot(dir);
testMatch(output, images[key + '-esm']);
testMatch(images[key + '-esm'], output);
});
});

Expand Down
6 changes: 2 additions & 4 deletions packages/cli/tests/subjects/custom-template/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
</head>
<body>
<h1>Guess what</h1>
<%= htmlWebpackPlugin.options.ssr({
url: '/'
}) %>
<script defer src="<%= htmlWebpackPlugin.files.chunks['bundle'].entry %>"></script>
<%= cli.ssr %>
<script defer src="<%= cli.entrypoints['bundle'] %>"></script>
</body>
</html>
8 changes: 3 additions & 5 deletions packages/cli/tests/subjects/custom-webpack/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@
<html lang="en">
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title %></title>
<title><%= cli.title %></title>
</head>
<body>
<h1>Guess what</h1>
<%= htmlWebpackPlugin.options.ssr({
url: '/'
}) %>
<script defer src="<%= htmlWebpackPlugin.files.chunks['bundle'].entry %>"></script>
<%= cli.ssr %>
<script defer src="<%= cli.entrypoints['bundle'] %>"></script>
</body>
</html>
Loading

0 comments on commit 754c3a2

Please sign in to comment.