Skip to content

Commit 224f3ee

Browse files
feat(html): add module.parser.html.sources option (#21022)
* feat(html): add module.parser.html.sources option When set to `false`, the HTML parser leaves URL-like attribute values (`<img src>`, `<link href>`, `<script src>`, …) untouched and does not turn `<script src>` / `<link rel="modulepreload">` / `<link rel="stylesheet">` into compilation entries. Inline `<script>` and `<style>` bodies are still processed. Use `webpackIgnore` comments or `IgnorePlugin` to skip individual URLs. * feat(html): support custom sources list in module.parser.html.sources `sources` now accepts `{ list: [...] }` in addition to a boolean. List entries may be `"..."` (inlines the built-in sources) or `{ tag, attribute, type: "src" | "srcset" }` to extract custom URL attributes (e.g. `data-src` for lazy-loaded images). `tag: "*"` matches any element. User-supplied sources are always plain URL rewrites — only built-in defaults promote `<script src>` / `<link rel="modulepreload" | "stylesheet">` into chunk entries. * refactor(html): drop tag:'*' from sources list; omit tag for any-element matching Removes the `tag: "*"` wildcard in favor of simply omitting `tag` to match any element. Also simplifies `resolveSources` and the parser walk: the disabled state now returns empty maps (single code path) and the per-element walk drops the redundant null-check on the resolved sources. * feat(html): inline sources array, add script/script-module/stylesheet/stylesheet-inline types `sources` is now `boolean | Array<...>` instead of `boolean | { list: Array<...> }` — the wrapping object only ever held one key. New `type` values let custom elements opt into the same handling as the built-in tags: - `script` — URL becomes a classic chunk entry (like `<script src>`) - `script-module` — URL becomes an ES-module chunk entry (like `<script type="module" src>`) - `stylesheet` — URL becomes a CSS chunk entry (like `<link rel="stylesheet">`) - `stylesheet-inline` — attribute value IS inline CSS text; routed through the CSS pipeline and the value is replaced with the processed CSS at render time `<script>`'s `type="module"` is no longer auto-detected when the user opts in via `type: "script"` / `"script-module"` — the user's choice wins. * refactor(html): unify user and default sources under a single kind field `SourceItem` now carries a `kind` field (string or attribute-driven function) that directly names the dependency to create — `src`, `script`, `script-module`, `modulepreload`, `stylesheet`, `stylesheet-inline`. The polymorphic defaults (`<link href>`, `<script src>`) move their attribute-driven decisions into a `kind` function alongside `filter`, so the parser walk has one code path regardless of whether a source came from the defaults or from the user's `sources` array. Internal chunk-kind renames to match the user-facing types: `classic` → `script`, `esm-script` → `script-module`, and `HtmlScriptElementKind`'s `script-classic` → `script`. * refactor(html): rename SourceItem.kind → type; inline resolveSources `SourceItem.type` now matches the user-facing `type` key in `sources: [{ tag, attribute, type }]`. Same rename for the local walk variable and `EntryScriptInfo.type`. `elementKind` stays — it's a separate concept (HTML element rendering shape, not the dispatch type). The standalone `resolveSources` helper is gone; the constructor builds the per-tag and any-tag maps directly. `sources: true`/`undefined` shares the `DEFAULT_SOURCES` reference (no allocation); `false` and arrays build fresh maps. `"..."` still expands defaults in place. * refactor(html): flatten DEFAULT_SOURCES into a single merged lookup `DEFAULT_SOURCES` is now a flat array of `SourceEntry` objects that shares its shape with user-supplied `sources` entries (`{ tag?, attribute, type, filter? }`). User arrays expand `"..."` via `flatMap(e => e === "..." ? DEFAULT_SOURCES : [e])`, so user entries can prepend, append, or override the built-in list with no special casing for defaults vs user input. Per-tag and any-tag maps collapsed into one `Map<string, SourceItem>` keyed by `${tag}\0${attribute}`; any-tag entries land under `\0${attribute}` and are queried only when `hasAnyTagSource` is set (empty for the defaults). The walk's lookup is now two `Map.get`s with no per-element gating. * perf(html): use Object.create(null) dicts and per-tag short-circuit Replaces the single composite-keyed Map with two null-prototype object dictionaries: a nested `sourcesByTag[tag][attribute]` table for the common per-tag case and a flat `anyTagSources[attribute]` table for tag-less user entries. Plain-object property access is significantly faster than `Map.get` once shapes stabilize, and avoids allocating a `${tag}\0${attribute}` string on every attribute lookup. Null prototypes also keep tag/attribute names like `__proto__` or `toString` from colliding with `Object.prototype`. Restores the per-element short-circuit: if a tag has no entry and no any-tag entries exist, the walk returns immediately without touching `pendingAttributes`. Most HTML elements (`<div>`, `<p>`, `<span>`, …) hit this fast path. Defaults are precomputed once at module load (`DEFAULT_RESOLVED_SOURCES`) and shared across every parser created with the default `sources` config — no per-parser allocation, and V8's inline caches stay hot across instances since the object shapes are identical. Microbenchmark (1M iterations): ~14x faster for typical HTML pages (mostly non-source elements) and ~4x faster when every element has a match. Behavior is unchanged. * refactor(html): collapse sources lookup to a single table + helper Drops `ResolvedSources` typedef, `EMPTY_RESOLVED_SOURCES`, and the `anyTagSources` / `hasAnyTagSource` fields on the parser. Everything lives in one `sourcesByTag` field — any-tag entries are stored under the sentinel key `ANY_TAG` (`"\0"`, which can't appear in an HTML tag name). Constructor is now a single ternary that either reuses the precomputed default table (the hot path — zero work per parser, zero allocation), reuses the shared empty table for `sources: false`, or calls `buildSourcesByTag` for a user array. `buildSourcesByTag` is the only function that actually runs per parser, and only in the user-array case. Walk still short-circuits on the per-tag dict access and falls back to the any-tag dict — both are null-prototype object property reads, same speed as before. * refactor(html): hand-write DEFAULT_SOURCES_BY_TAG in resolved shape Drops the separate `DEFAULT_SOURCES` array and the module-load loop that built `DEFAULT_SOURCES_BY_TAG` from it. The lookup table is now written directly with shared `PLAIN_SRC` / `PLAIN_SRCSET` singletons and a small `dict()` helper that null-prototypes object literals. `buildSourcesByTag` shrinks to user-array handling only: a `"..."` literal copies tag buckets straight out of `DEFAULT_SOURCES_BY_TAG` via `Object.assign`, no intermediate flat array. The constructor passes `userSources` directly — no `flatMap` allocation either. The walk hot path is unchanged. * refactor(html): drop dict()/Object.create(null) for sources tables HTML tag and attribute names come from a known vocabulary, and these tables are never mutated after construction, so the prototype-pollution guard isn't pulling its weight. Plain object literals are simpler and just as fast for the static lookup pattern used here. `DEFAULT_SOURCES_BY_TAG`, `EMPTY_SOURCES_BY_TAG`, and the per-tag buckets created by `buildSourcesByTag` are all plain `{}` now. No helper, no `Object.create(null)`, no `Object.assign` ceremony for the defaults. * refactor(html): build tag buckets via spread; cache anyTagSources `buildSourcesByTag` no longer keeps a mutable per-tag `bucket` local or guards `if (!bucket) byTag[tag] = bucket = {}`. Each write is a single expression — `byTag[tag] = { ...byTag[tag], [attr]: item }` — that works whether the tag has been seen or not (spreading `undefined` is a no-op). `"..."` expansion uses the same idiom to merge default buckets in place. The any-tag bucket (`sourcesByTag[ANY_TAG]`) is now cached once on the parser as `this.anyTagSources`. The walk's per-element short-circuit and per-attribute fallback both read this cached value instead of re-indexing into `sourcesByTag` with the sentinel each time. * perf(html): fold any-tag entries into per-tag buckets at build time The walk's per-attribute lookup is now a single property read (`tagSources[attr]`) instead of a `(tag && tag[attr]) || (any && any[attr])` chain. Any-tag entries are folded into every per-tag bucket once at construction (tag-specific still wins via spread order), so the fallback is already baked in. `buildSourcesByTag` returns `{ byTag, anyTag }`; the parser stores both fields (the bare `anyTag` is still used as the per-element fallback for tags missing from `byTag`, e.g. `<custom-elem>` against a user any-tag rule). The default and `false` configs share precomputed `ResolvedSources` constants, so the constructor is two field assignments off a literal pick. The `ANY_TAG` sentinel and the inline `sourcesByTag[ANY_TAG]` lookup are gone — the data layout itself encodes the fallback. Microbenchmark of the matching-element path: ~10% faster (137 ms → 126 ms over 1M iters). Non-matching elements still hit the per-element short-circuit and are unchanged. * refactor(html): inline source resolution into the constructor Drops `buildSourcesByTag`, `ResolvedSources` typedef, `DEFAULT_RESOLVED`, and `EMPTY_RESOLVED`. The default and `false` cases are now two-line early returns in the constructor that just reference the precomputed `DEFAULT_SOURCES_BY_TAG` / `EMPTY_SOURCES_BY_TAG` tables — no helper call, no wrapper struct, no per-parser allocation. Only the user-array path runs build logic, and it sits in the constructor where it's used. Same spread-based build, same any-tag fold, same walk lookup — purely a structural simplification. * refactor(html): make default source path do nothing extra Drops the `options && options.sources` guard — `createParser` always passes a parser-options object, so `options.sources` is safe to read directly. The default-source state is now set unconditionally at the top of the constructor (`this.sourcesByTag = DEFAULT_SOURCES_BY_TAG; this.anyTagSources = undefined`), and the no-user-option path is just a single `return` — no loop, no branch, no helper. The user-array path still runs the build, but the `"..."` spread order is flipped so user entries always override defaults regardless of where `"..."` sits in the array (the position-aware semantic wasn't exercised by any test and produced counter-intuitive behavior when `"..."` came after user entries). * feat(html): default module.parser.html.sources to true Set the parser default explicitly in `applyModuleDefaults` so the resolved config carries `sources: true` instead of leaving the key undefined and relying on HtmlParser to interpret undefined as "use the built-in sources". Updates `Defaults.unittest.js` snapshots (and the regenerated `types.d.ts`) to reflect the new key. Behavior unchanged: HtmlParser still treats `true` (and `undefined`) the same way — both reference the precomputed `DEFAULT_SOURCES_BY_TAG` table. * refactor(html): make srcset a first-class SourceItem type `SourceItem` is now `{ type, filter }` — no separate `parse` field. `type` carries `"srcset"` as a real value (it's part of `SourceType` now), matching the user-facing schema. The walk derives the parser from the resolved type (`parseSrcset` for `"srcset"`, `parseSrc` otherwise) and dispatches `"src"` and `"srcset"` to the same `HtmlSourceDependency` branch. Drops the `isSrcset` mapping from the user-array build — user entries are stored as-is. Default entries that were `{ parse: parseSrcset, type: "src" }` are now just `{ type: "srcset" }`, including the shared `PLAIN_SRCSET` singleton. `SourceEntry` and `SourceItem` are now structurally the same modulo `type` being a string in `SourceEntry` and `SourceType | resolver` in `SourceItem`. types.d.ts regenerated. * refactor(html): apply defaults with a single shallow spread `"..."` no longer triggers an inner `Object.keys(DEFAULT_SOURCES_BY_TAG)` loop. The constructor checks once whether `"..."` is in the array and, if so, seeds `byTag` with a single shallow spread of `DEFAULT_SOURCES_BY_TAG`. Per-tag writes during the user loop use spread (`{ ...byTag[tag], [attr]: item }`), so default buckets are safely aliased until a user entry forces a new object. Same semantics as before (`"..."` opts the defaults in; user entries override), just one fewer loop and one fewer object allocation per expanded default tag. * refactor(html): derive parser env from compilation, not constructor args HtmlParser's constructor takes only `options` now. `hashFunction`, `context`, `outputModule`, and `css` are pulled from `state.compilation` (outputOptions / compiler.context / options.experiments.css) at the top of `parse()` and used as locals through the rest of the method — they're not stored on the parser instance. HtmlModulesPlugin's `createParser` tap drops the four extra arguments and the local `cssEnabled` computation; the call site is now just `new HtmlParser(parserOptions)`. types.d.ts regenerated to drop the corresponding fields from the declared shape. * fix(html): harden sources lookup (null-proto tables, UTF-8 CSS) - Build the tag/attribute lookup tables with null prototypes so HTML names that collide with Object.prototype keys (`__proto__`, `constructor`, `toString`, …) can't resolve to inherited values, create bogus dependencies, or bypass `sources: false`. - Base64-encode (UTF-8) inline CSS data URIs — both `<style>` bodies and `stylesheet-inline` attributes — so non-ASCII CSS round-trips instead of being corrupted by `decodeDataURI`'s ASCII path. - Correct stale `classic`/`esm-script` comments to `script`/`script-module`. - Add proto-bypass and non-ASCII-CSS regression tests. * fix(html): resolve pre-existing tsc and schema-lint errors - Add the missing `description` to `parser.html.sources` array `items` (schemas-lint requires every items schema to be documented). - Cast `module.parser[HTML_MODULE_TYPE]` to `NonNullable<ParserOptionsByModuleTypeKnown[HTML_MODULE_TYPE]>` in defaults, matching the asset/json/css parser-default pattern, so the `"sources"` key is assignable instead of `never`. * fix(html): emit real script/link siblings for custom-element sources A user `sources` entry can map a custom element (e.g. `<my-script src>`) onto `type: script`/`script-module`/`stylesheet`. When such an entry was split across multiple chunks (runtimeChunk/splitChunks), the template cloned the custom element verbatim and appended `</script>`, producing invalid, non-executing markup like `<my-script src="runtime.js"></script>`. Detect whether the originating tag is the native element for its kind (`<script>` / `<link>`); clone only native tags (to preserve attributes like `defer`/`media`), and synthesize a real `<script>`/`<link>` sibling for custom elements, copying the CSP/fetch attributes. Adds a parser-sources-custom-tag-siblings configCase exercising custom `script` and `script-module` sources with runtimeChunk. * fix(html): module-script siblings for custom elements under output.module When `output.module` is enabled the emitted chunks are ESM, so a custom element mapped to `type: "script"` (e.g. `<my-script src>`) must get `<script type="module">` sibling tags for its runtime/split chunks — a classic `<script>` sibling can't load an ES module. Derive `willBeModuleScript`/`elementKind` from `outputModule` for any `type: "script"` source, not only a native `<script>`; the in-place `type`-attribute rewrite stays native-only (a custom element's attributes are the user's to own). Adds parser-sources-custom-tag-module-siblings exercising a custom `script` source with output.module + runtimeChunk. * test(html): refresh style-tag persistent-cache snapshot The base64 inline-CSS change updated ConfigTest.snap but not the parallel ConfigCacheTest.snap, breaking ConfigCacheTestCases. Regenerate it so both carry the `data:text/css;base64,` headers and the non-ASCII `café →` rule. * test(cli): add module.parser.html.sources flags to getArguments snapshot The `sources` schema option generates `--module-parser-html-sources` (and its `-attribute`/`-tag`/`-type`/`-reset` companions), but the Cli `getArguments` snapshot never captured them, failing the basic test job. Regenerate it so the snapshot matches the schema-derived CLI flags. * chore: regenerate WebpackOptions validator after rebase onto main The rebase hit a conflict in the generated `schemas/WebpackOptions.check.js` (main added `output.environment.let`); regenerate it from the merged schema so the validator carries both that option and `module.parser.html.sources`. * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <[email protected]> --------- Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent 5fe4414 commit 224f3ee

53 files changed

Lines changed: 1243 additions & 450 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Add `module.parser.html.sources` option to disable or customize URL-attribute extraction for HTML modules, with `script` / `script-module` / `stylesheet` / `stylesheet-inline` types for custom attributes

‎cspell.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@
276276
"sourcemapped",
277277
"spectest",
278278
"splitted",
279+
"srcset",
279280
"stylesheet",
280281
"stringable",
281282
"slsh",

‎declarations/WebpackOptions.d.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3522,6 +3522,39 @@ export interface HtmlGeneratorOptions {
35223522
*/
35233523
extract?: boolean;
35243524
}
3525+
/**
3526+
* Parser options for html modules.
3527+
*/
3528+
export interface HtmlParserOptions {
3529+
/**
3530+
* Configure extraction of URL-like attribute values (e.g. `<img src>`, `<link href>`, `<script src>`) as webpack dependencies. `true` (default) uses the built-in source list; `false` disables extraction entirely so attributes are left untouched and `<script src>` / `<link rel="modulepreload">` / `<link rel="stylesheet">` no longer become compilation entries; an array lets you customize which `tag`/`attribute` pairs are treated as URLs and how they are bundled. Use the string `"..."` inside the array to inline the defaults. Inline `<script>` and `<style>` bodies are always processed. Use `webpackIgnore` comments or `IgnorePlugin` to skip individual URLs.
3531+
*/
3532+
sources?:
3533+
| (
3534+
| "..."
3535+
| {
3536+
/**
3537+
* Attribute name whose value is treated as a URL.
3538+
*/
3539+
attribute: string;
3540+
/**
3541+
* Tag name to match. Omit to match any tag.
3542+
*/
3543+
tag?: string;
3544+
/**
3545+
* How the attribute value should be parsed and bundled. `src` extracts a single URL as a plain asset; `srcset` parses a `srcset`-style list of candidate URLs as plain assets; `script` and `script-module` emit a classic / ES-module chunk entry like `<script src>` and `<script type="module" src>`; `stylesheet` emits a CSS chunk entry like `<link rel="stylesheet">`; `stylesheet-inline` treats the attribute value as inline CSS text and bundles it through the CSS pipeline (the attribute's content is replaced with the processed CSS at render time, like an inline `<style>` body).
3546+
*/
3547+
type:
3548+
| "src"
3549+
| "srcset"
3550+
| "script"
3551+
| "script-module"
3552+
| "stylesheet"
3553+
| "stylesheet-inline";
3554+
}
3555+
)[]
3556+
| boolean;
3557+
}
35253558
/**
35263559
* Parser options for javascript modules.
35273560
*/
@@ -4366,6 +4399,10 @@ export interface ParserOptionsByModuleTypeKnown {
43664399
* Parser options for css/auto and css/module modules.
43674400
*/
43684401
"css/module"?: CssAutoOrModuleParserOptions;
4402+
/**
4403+
* Parser options for html modules.
4404+
*/
4405+
html?: HtmlParserOptions;
43694406
/**
43704407
* Parser options for javascript modules.
43714408
*/

‎lib/config/defaults.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,6 +1090,18 @@ const applyModuleDefaults = (
10901090
// modules (including imported ones); `extract: false` disables it
10911091
// everywhere.
10921092
F(module.generator, HTML_MODULE_TYPE, () => ({}));
1093+
// `module.parser.html.sources` defaults to `true` — HtmlParser uses
1094+
// the built-in source list to extract URL-like attributes (`<img
1095+
// src>`, `<link href>`, `<script src>`, …) as webpack dependencies.
1096+
// Users may pass `false` to disable extraction entirely or an array
1097+
// (with `"..."` to include the defaults) to customize it.
1098+
F(module.parser, HTML_MODULE_TYPE, () => ({}));
1099+
D(
1100+
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[HTML_MODULE_TYPE]>} */
1101+
(module.parser[HTML_MODULE_TYPE]),
1102+
"sources",
1103+
true
1104+
);
10931105
}
10941106

10951107
A(module, "defaultRules", () => {

‎lib/dependencies/HtmlScriptSrcDependency.js‎

Lines changed: 85 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const ModuleDependency = require("./ModuleDependency");
2323
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
2424
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
2525

26-
/** @typedef {"script-classic" | "script-module" | "modulepreload" | "stylesheet"} HtmlScriptElementKind */
26+
/** @typedef {"script" | "script-module" | "modulepreload" | "stylesheet"} HtmlScriptElementKind */
2727

2828
class HtmlScriptSrcDependency extends ModuleDependency {
2929
/**
@@ -51,7 +51,7 @@ class HtmlScriptSrcDependency extends ModuleDependency {
5151
/** @type {string} */
5252
this._category = category || "commonjs";
5353
/** @type {HtmlScriptElementKind} */
54-
this.elementKind = elementKind || "script-classic";
54+
this.elementKind = elementKind || "script";
5555
/** @type {number} */
5656
this.tagStart = tagStart === undefined ? -1 : tagStart;
5757
/** @type {number} */
@@ -295,6 +295,36 @@ const buildStylesheetLink = (originalTag, href) => {
295295
return `<link rel="stylesheet" href="${safeHref}"${extra}>`;
296296
};
297297

298+
const COPYABLE_SCRIPT_ATTRS = ["nonce", "crossorigin", "referrerpolicy"];
299+
300+
/**
301+
* Build a fresh `<script src="…">` for a JS chunk pulled in by a custom
302+
* (non-`<script>`) element that the user mapped to `type: "script"` /
303+
* `"script-module"`. Cloning the custom element verbatim and appending
304+
* `</script>` (as `cloneTagWithUrl` does for a real `<script>`) would emit
305+
* mismatched, non-executing markup such as `<my-script src="…"></script>`,
306+
* so synthesize a real script element instead — copying only the CSP/fetch
307+
* attributes, since the custom element's other attributes have no defined
308+
* meaning on a `<script>`.
309+
* @param {string} originalTag the originating element's source text
310+
* @param {string} src URL for the script
311+
* @param {boolean} isModule whether to emit `type="module"`
312+
* @returns {string} the sibling `<script>` tag's HTML
313+
*/
314+
const buildScriptTag = (originalTag, src, isModule) => {
315+
let extra = "";
316+
for (const attr of COPYABLE_SCRIPT_ATTRS) {
317+
const re = new RegExp(
318+
`\\s${attr}(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+))?(?=[\\s/>])`,
319+
"i"
320+
);
321+
const m = originalTag.match(re);
322+
if (m) extra += m[0];
323+
}
324+
const safeSrc = src.replace(/"/g, "&quot;");
325+
return `<script${isModule ? ' type="module"' : ""} src="${safeSrc}"${extra}></script>`;
326+
};
327+
298328
/**
299329
* Clone the original `<script>`/`<link>` opening tag with its `src`/`href`
300330
* value swapped for a different chunk URL. Reusing the source text verbatim
@@ -349,6 +379,25 @@ const cloneTagWithUrl = (
349379
: `${body}</script>`;
350380
};
351381

382+
/**
383+
* Whether `originalTag` is the native HTML element that loads a chunk of
384+
* `elementKind` — `<script>` for `script`/`script-module`, `<link>` for
385+
* `stylesheet`/`modulepreload`. A user can map an arbitrary custom element
386+
* (e.g. `<my-script src>`) onto a `script`/`stylesheet` source `type`; for
387+
* those, the original tag must not be cloned when emitting sibling tags for
388+
* extra chunks, because the clone would be invalid markup.
389+
* @param {string} originalTag the originating tag's source text
390+
* @param {HtmlScriptElementKind} elementKind element kind
391+
* @returns {boolean} true when the tag is the native element for the kind
392+
*/
393+
const isNativeTagForKind = (originalTag, elementKind) => {
394+
const nativeTag =
395+
elementKind === "stylesheet" || elementKind === "modulepreload"
396+
? "link"
397+
: "script";
398+
return new RegExp(`^<${nativeTag}(?=[\\s/>])`, "i").test(originalTag);
399+
};
400+
352401
HtmlScriptSrcDependency.Template = class HtmlScriptSrcDependencyTemplate extends (
353402
ModuleDependency.Template
354403
) {
@@ -404,6 +453,11 @@ HtmlScriptSrcDependency.Template = class HtmlScriptSrcDependencyTemplate extends
404453
const originalTag = originalContent.slice(dep.tagStart, dep.tagOpenEnd);
405454
const srcStartInTag = dep.range[0] - dep.tagStart;
406455
const srcEndInTag = dep.range[1] - dep.tagStart;
456+
// A user-configured source `type` can sit on an arbitrary custom
457+
// element; cloning that element for sibling chunks would emit
458+
// invalid markup (e.g. `<my-script …></script>`), so fall back to
459+
// synthesizing real native tags for non-native originating elements.
460+
const tagIsNative = isNativeTagForKind(originalTag, dep.elementKind);
407461

408462
/**
409463
* @param {Chunk} chunk chunk to emit a sibling tag for
@@ -412,18 +466,39 @@ HtmlScriptSrcDependency.Template = class HtmlScriptSrcDependencyTemplate extends
412466
*/
413467
const buildSibling = (chunk, kind) => {
414468
const url = HtmlGenerator.makeChunkUrlSentinel(chunk, kind);
415-
if (kind === "css" && !isStylesheet) {
416-
// Originating tag is `<script>` (or `<link rel=modulepreload>`)
417-
// but this chunk is CSS — emit a fresh `<link>` rather than
418-
// cloning the script.
469+
if (kind === "css") {
470+
// A CSS chunk is always loaded via `<link rel="stylesheet">`.
471+
// Clone only when the entry tag is itself a native `<link
472+
// rel="stylesheet">` (so attributes like `media` carry over);
473+
// a `<script>` entry that imported CSS, or a custom element,
474+
// gets a freshly synthesized `<link>`.
475+
if (isStylesheet && tagIsNative) {
476+
return cloneTagWithUrl(
477+
originalTag,
478+
srcStartInTag,
479+
srcEndInTag,
480+
url,
481+
dep.elementKind
482+
);
483+
}
419484
return buildStylesheetLink(originalTag, url);
420485
}
421-
return cloneTagWithUrl(
486+
// A JS chunk is loaded via `<script>`. Clone a native `<script>`
487+
// verbatim; synthesize a real `<script>` for custom elements that
488+
// were mapped to `type: script`/`script-module`.
489+
if (tagIsNative) {
490+
return cloneTagWithUrl(
491+
originalTag,
492+
srcStartInTag,
493+
srcEndInTag,
494+
url,
495+
dep.elementKind
496+
);
497+
}
498+
return buildScriptTag(
422499
originalTag,
423-
srcStartInTag,
424-
srcEndInTag,
425500
url,
426-
dep.elementKind
501+
dep.elementKind === "script-module"
427502
);
428503
};
429504

‎lib/html/HtmlModulesPlugin.js‎

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ const HtmlGenerator = require("./HtmlGenerator");
2222
const HtmlParser = require("./HtmlParser");
2323

2424
/** @typedef {import("../Compiler")} Compiler */
25-
/** @typedef {{ request: string, entryName: string, kind: "classic" | "esm-script" | "modulepreload" | "stylesheet" }} EntryScriptInfo */
25+
/** @typedef {{ request: string, entryName: string, type: "script" | "script-module" | "modulepreload" | "stylesheet" }} EntryScriptInfo */
2626

2727
const PLUGIN_NAME = "HtmlModulesPlugin";
2828

@@ -44,6 +44,11 @@ const generatorValidationOptions = {
4444
baseDataPath: "generator"
4545
};
4646

47+
const parserValidationOptions = {
48+
name: "Html Modules Plugin",
49+
baseDataPath: "parser"
50+
};
51+
4752
class HtmlModulesPlugin {
4853
/**
4954
* `output.hashFunction`/`hashSalt`/`hashDigest`/`hashDigestLength`
@@ -83,8 +88,8 @@ class HtmlModulesPlugin {
8388
const sentinelResolvedSourceCache = new Map();
8489

8590
// `<script src>` and `<link rel="modulepreload">` references collected
86-
// by HtmlParser become real compilation entries here. The classic
87-
// and esm-script groups are chained via a leader-only dependOn so
91+
// by HtmlParser become real compilation entries here. The `script`
92+
// and `script-module` groups are chained via a leader-only dependOn so
8893
// they share a runtime — the first entry of the group owns it and
8994
// every subsequent entry sets `dependOn: [leader]`. Modulepreload
9095
// entries are emitted as independent entries (no dependOn) so they
@@ -112,7 +117,7 @@ class HtmlModulesPlugin {
112117
const context = /** @type {string} */ (module.context);
113118

114119
for (const [groupKind, group] of Object.entries(htmlEntryScripts)) {
115-
// Only the script chains (`classic`, `esm-script`) need a
120+
// Only the script chains (`script`, `script-module`) need a
116121
// shared runtime via leader-only `dependOn` — the others
117122
// either preload without executing (`modulepreload`) or
118123
// produce CSS chunks (`stylesheet`) which have no runtime
@@ -258,21 +263,20 @@ class HtmlModulesPlugin {
258263
ConstDependency,
259264
new ConstDependency.Template()
260265
);
261-
const cssEnabled = Boolean(
262-
compiler.options.experiments && compiler.options.experiments.css
263-
);
264266
normalModuleFactory.hooks.createParser
265267
.for(HTML_MODULE_TYPE)
266-
.tap(
267-
PLUGIN_NAME,
268-
() =>
269-
new HtmlParser(
270-
compilation.outputOptions.hashFunction,
271-
compiler.context,
272-
compilation.outputOptions.module,
273-
cssEnabled
274-
)
275-
);
268+
.tap(PLUGIN_NAME, (parserOptions) => {
269+
compiler.validate(
270+
() => getSchema("HtmlParserOptions"),
271+
parserOptions,
272+
parserValidationOptions,
273+
(options) =>
274+
require("../../schemas/plugins/HtmlParserOptions.check")(
275+
options
276+
)
277+
);
278+
return new HtmlParser(parserOptions);
279+
});
276280

277281
normalModuleFactory.hooks.createGenerator
278282
.for(HTML_MODULE_TYPE)

0 commit comments

Comments
 (0)