Skip to content

Commit 22dd9bb

Browse files
authored
perf(html): skip JS sentinel scans on chunks without HTML (#21974)
Add chunkHasHtml and early-exit jsHooks.render before ConcatSource.source(), with an HTML-entry benchmark case.
1 parent 5b38bcb commit 22dd9bb

8 files changed

Lines changed: 133 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Skip JS render sentinel scans on chunks without HTML.

‎lib/html/HtmlModulesPlugin.js‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const ConstDependency = require("../dependencies/ConstDependency");
1919
const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
2020
const WebpackError = require("../errors/WebpackError");
2121
const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin");
22+
const ConcatenatedModule = require("../optimize/ConcatenatedModule");
2223
const { compareModulesByFullName } = require("../util/comparators");
2324
const createHash = require("../util/createHash");
2425
const createHooksRegistry = require("../util/createHooksRegistry");
@@ -55,6 +56,8 @@ const getHtmlGenerator = memoize(() => require("./HtmlGenerator"));
5556
/** @typedef {import("../../declarations/WebpackOptions").OutputHtmlOptions["favicon"]} FaviconOption */
5657
/** @typedef {import("../../declarations/WebpackOptions").OutputHtmlOptions["manifest"]} ManifestOption */
5758
/** @typedef {Exclude<HtmlFaviconIcon, string>} FaviconIcon */
59+
/** @import Chunk from "../Chunk" */
60+
/** @import ChunkGraph from "../ChunkGraph" */
5861
/** @import Compiler from "../Compiler" */
5962
/** @import { HtmlModuleBuildInfo } from "./HtmlModule" */
6063
/** @import HtmlParser from "./HtmlParser" */
@@ -1211,6 +1214,16 @@ class HtmlModulesPlugin {
12111214
jsHooks.render.tap(PLUGIN_NAME, (source, renderContext) => {
12121215
// No HTML modules ⇒ no sentinels; skip materializing the JS source.
12131216
if (htmlModules.size === 0) return source;
1217+
// Chunks without HTML modules can't carry HTML sentinels — avoid
1218+
// ConcatSource.source() on the common pure-JS chunk path.
1219+
if (
1220+
!HtmlModulesPlugin.chunkHasHtml(
1221+
renderContext.chunk,
1222+
compilation.chunkGraph
1223+
)
1224+
) {
1225+
return source;
1226+
}
12141227
const raw = source.source();
12151228
if (typeof raw !== "string") return source;
12161229
// Every sentinel shares this prefix — one scan answers the common
@@ -1281,6 +1294,29 @@ class HtmlModulesPlugin {
12811294
}
12821295
);
12831296
}
1297+
1298+
/**
1299+
* Returns true, when the chunk has html.
1300+
* @param {Chunk} chunk chunk
1301+
* @param {ChunkGraph} chunkGraph chunk graph
1302+
* @returns {boolean} true, when the chunk has html
1303+
*/
1304+
static chunkHasHtml(chunk, chunkGraph) {
1305+
if (chunkGraph.getChunkModulesIterableBySourceType(chunk, HTML_TYPE)) {
1306+
return true;
1307+
}
1308+
// Scope-hoisted HTML loses HTML_TYPE on the ConcatenatedModule, but its
1309+
// JS export can still carry unresolved sentinels that need this path.
1310+
for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
1311+
if (module instanceof HtmlModule) return true;
1312+
if (module instanceof ConcatenatedModule) {
1313+
for (const inner of module.modules) {
1314+
if (inner instanceof HtmlModule) return true;
1315+
}
1316+
}
1317+
}
1318+
return false;
1319+
}
12841320
}
12851321

12861322
/**
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<!doctype html>
2+
<html>
3+
<body>
4+
<script type="module" src="./main.js"></script>
5+
</body>
6+
</html>
7+
<!-- watch test --><!-- watch test --><!-- watch test --><!-- watch test --><!-- watch test -->
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import * as mod from "./generated/module.js";
2+
export { mod };
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import fs from "fs/promises";
2+
import { dirname, resolve } from "path";
3+
import { fileURLToPath } from "url";
4+
import createTree from "../../harness/benchmark/create-tree.mjs";
5+
import memoryScaledCount from "../../harness/benchmark/scale.mjs";
6+
7+
// HTML entry + many async JS chunks: htmlModules is non-empty while most chunks
8+
// lack HTML_TYPE, so chunkHasHtml can skip ConcatSource.source() on them.
9+
export async function setup() {
10+
const __dirname = dirname(fileURLToPath(import.meta.url));
11+
const generated = resolve(__dirname, "./generated");
12+
13+
await fs.rm(generated, { recursive: true, force: true });
14+
await createTree(generated, false, memoryScaledCount(50, 150), 0);
15+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/** @type {import("../../..").Configuration} */
2+
export default {
3+
entry: "./index.html",
4+
target: "web",
5+
experiments: {
6+
html: true
7+
},
8+
// Leave minify off so HtmlModulesPlugin's jsHooks.render isn't drowned by terser.
9+
optimization: {
10+
minimize: false
11+
}
12+
};

‎test/harness/benchmark/benchmark.worker.mjs‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -792,7 +792,10 @@ function buildConfiguration(test, baseline, realConfig, scenario, testDirectory)
792792
? path.resolve(
793793
testDirectory,
794794
config.entry
795-
? /\.(?:c|m)?js$/.test(config.entry)
795+
? // Keep entries that already have an extension (JS or HTML).
796+
// Bare names still get `.js` — the historical default entry shape.
797+
/\.(?:c|m)?js$/i.test(config.entry) ||
798+
/\.html$/i.test(config.entry)
796799
? config.entry
797800
: `${config.entry}.js`
798801
: "./index.js"
@@ -868,6 +871,51 @@ function addBuildBench({
868871
);
869872
}
870873

874+
/**
875+
* Resolve the on-disk file the watch scenario rewrites to trigger a rebuild.
876+
* @param {NonNullable<Configuration["entry"]>} entry webpack entry
877+
* @returns {string} absolute path of one entry file
878+
*/
879+
const resolveWatchEntryPath = (entry) => {
880+
if (typeof entry === "string") return path.resolve(entry);
881+
if (Array.isArray(entry)) {
882+
const first = entry.find((item) => typeof item === "string");
883+
if (typeof first === "string") return path.resolve(first);
884+
} else if (entry && typeof entry === "object") {
885+
for (const value of Object.values(entry)) {
886+
if (typeof value === "string") return path.resolve(value);
887+
if (Array.isArray(value)) {
888+
const first = value.find((item) => typeof item === "string");
889+
if (typeof first === "string") return path.resolve(first);
890+
} else if (
891+
value &&
892+
typeof value === "object" &&
893+
"import" in value &&
894+
value.import
895+
) {
896+
const imp = value.import;
897+
if (typeof imp === "string") return path.resolve(imp);
898+
if (Array.isArray(imp)) {
899+
const first = imp.find((item) => typeof item === "string");
900+
if (typeof first === "string") return path.resolve(first);
901+
}
902+
}
903+
}
904+
}
905+
throw new Error("Watch bench needs a string path in `entry`.");
906+
};
907+
908+
/**
909+
* Append a no-op change that keeps the entry parseable (JS statement or HTML comment).
910+
* @param {string} entryPath entry file path
911+
* @param {string} originalContent original file contents
912+
* @returns {string} mutated contents
913+
*/
914+
const mutateWatchEntryContent = (entryPath, originalContent) =>
915+
/\.html$/i.test(entryPath)
916+
? `${originalContent}<!-- watch test -->`
917+
: `${originalContent};console.log('watch test')`;
918+
871919
/**
872920
* @param {object} params params
873921
* @param {Bench} params.bench bench
@@ -882,7 +930,7 @@ async function addWatchBench({ bench, taskName, collectBy, webpack, config }) {
882930
throw new Error(`No entry for "${taskName}" bench.`);
883931
}
884932

885-
const entry = path.resolve(/** @type {string} */ (config.entry));
933+
const entry = resolveWatchEntryPath(config.entry);
886934
const originalEntryContent = await fs.readFile(entry, "utf8");
887935

888936
/** @type {Watching | undefined} */
@@ -937,7 +985,7 @@ async function addWatchBench({ bench, taskName, collectBy, webpack, config }) {
937985
(resolve, reject) => {
938986
writeFile(
939987
entry,
940-
`${originalEntryContent};console.log('watch test')`,
988+
mutateWatchEntryContent(entry, originalEntryContent),
941989
(err) => {
942990
if (err) {
943991
reject(err);

‎types.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10309,6 +10309,11 @@ declare class HtmlModulesPlugin {
1030910309
outputOptions: Output
1031010310
): ChunkFilenameTemplate;
1031110311

10312+
/**
10313+
* Returns true, when the chunk has html.
10314+
*/
10315+
static chunkHasHtml(chunk: Chunk, chunkGraph: ChunkGraph): boolean;
10316+
1031210317
/**
1031310318
* Per-compilation hooks for the experimental HTML support.
1031410319
*/

0 commit comments

Comments
 (0)