Skip to content

fix: hmr crash in some situations #1140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 30 additions & 25 deletions src/hmr/hotModuleReplacement.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
func-names
*/

// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @typedef {any} TODO */

const normalizeUrl = require("./normalize-url");

const srcByModuleId = Object.create(null);
Expand Down Expand Up @@ -47,9 +44,11 @@ function debounce(fn, time) {
*/
function noop() {}

/** @typedef {(filename?: string) => string[]} GetScriptSrc */

/**
* @param {string | number} moduleId a module id
* @returns {TODO} current script url
* @returns {GetScriptSrc} current script url
*/
function getCurrentScriptUrl(moduleId) {
let src = srcByModuleId[moduleId];
Expand All @@ -69,13 +68,10 @@ function getCurrentScriptUrl(moduleId) {
srcByModuleId[moduleId] = src;
}

/**
* @param {string} fileMap file map
* @returns {null | string[]} normalized files
*/
/** @type {GetScriptSrc} */
return function (fileMap) {
if (!src) {
return null;
return [];
}

const splitResult = src.split(/([^\\/]+)\.js$/);
Expand Down Expand Up @@ -114,8 +110,10 @@ function isUrlRequest(url) {
return true;
}

/** @typedef {HTMLLinkElement & { isLoaded: boolean, visited: boolean }} HotHTMLLinkElement */

/**
* @param {TODO} el html link element
* @param {HotHTMLLinkElement} el html link element
* @param {string=} url a URL
*/
function updateCss(el, url) {
Expand Down Expand Up @@ -145,7 +143,9 @@ function updateCss(el, url) {

el.visited = true;

const newEl = el.cloneNode();
const newEl =
/** @type {HotHTMLLinkElement} */
(el.cloneNode());

newEl.isLoaded = false;

Expand All @@ -155,7 +155,10 @@ function updateCss(el, url) {
}

newEl.isLoaded = true;
el.parentNode.removeChild(el);

if (el.parentNode) {
el.parentNode.removeChild(el);
}
});

newEl.addEventListener("error", () => {
Expand All @@ -164,21 +167,26 @@ function updateCss(el, url) {
}

newEl.isLoaded = true;
el.parentNode.removeChild(el);

if (el.parentNode) {
el.parentNode.removeChild(el);
}
});

newEl.href = `${url}?${Date.now()}`;

if (el.nextSibling) {
el.parentNode.insertBefore(newEl, el.nextSibling);
} else {
el.parentNode.appendChild(newEl);
if (el.parentNode) {
if (el.nextSibling) {
el.parentNode.insertBefore(newEl, el.nextSibling);
} else {
el.parentNode.appendChild(newEl);
}
}
}

/**
* @param {string} href href
* @param {TODO} src src
* @param {string[]} src src
* @returns {undefined | string} a reload url
*/
function getReloadUrl(href, src) {
Expand All @@ -192,6 +200,7 @@ function getReloadUrl(href, src) {
*/
// eslint-disable-next-line array-callback-return
(url) => {
// @ts-expect-error fix me in the next major release
// eslint-disable-next-line unicorn/prefer-includes
if (href.indexOf(src) > -1) {
ret = url;
Expand All @@ -203,14 +212,10 @@ function getReloadUrl(href, src) {
}

/**
* @param {string=} src source
* @param {string[]} src source
* @returns {boolean} true when loaded, otherwise false
*/
function reloadStyle(src) {
if (!src) {
return false;
}

const elements = document.querySelectorAll("link");
let loaded = false;

Expand Down Expand Up @@ -256,8 +261,8 @@ function reloadAll() {

/**
* @param {number | string} moduleId a module id
* @param {TODO} options options
* @returns {TODO} wrapper function
* @param {{ filename?: string, locals?: boolean }} options options
* @returns {() => void} wrapper function
*/
module.exports = function (moduleId, options) {
if (noDocument) {
Expand Down
43 changes: 21 additions & 22 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const {
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("webpack").ChunkGraph} ChunkGraph */
/** @typedef {import("webpack").Chunk} Chunk */
/** @typedef {Parameters<import("webpack").Chunk["isInGroup"]>[0]} ChunkGroup */
/** @typedef {import("webpack").ChunkGroup} ChunkGroup */
/** @typedef {import("webpack").Module} Module */
/** @typedef {import("webpack").Dependency} Dependency */
/** @typedef {import("webpack").sources.Source} Source */
Expand All @@ -30,6 +30,9 @@ const {
/** @typedef {import("webpack").AssetInfo} AssetInfo */
/** @typedef {import("./loader.js").Dependency} LoaderDependency */

/** @typedef {NonNullable<Required<Configuration>['output']['filename']>} Filename */
/** @typedef {NonNullable<Required<Configuration>['output']['chunkFilename']>} ChunkFilename */

/**
* @typedef {object} LoaderOptions
* @property {string | ((resourcePath: string, rootContext: string) => string)=} publicPath public path
Expand All @@ -41,8 +44,8 @@ const {

/**
* @typedef {object} PluginOptions
* @property {Required<Configuration>['output']['filename']=} filename filename
* @property {Required<Configuration>['output']['chunkFilename']=} chunkFilename chunk filename
* @property {Filename=} filename filename
* @property {ChunkFilename=} chunkFilename chunk filename
* @property {boolean=} ignoreOrder true when need to ignore order, otherwise false
* @property {string | ((linkTag: HTMLLinkElement) => void)=} insert link insert place or a custom insert function
* @property {Record<string, string>=} attributes link attributes
Expand All @@ -53,8 +56,8 @@ const {

/**
* @typedef {object} NormalizedPluginOptions
* @property {Required<Configuration>['output']['filename']} filename filename
* @property {Required<Configuration>['output']['chunkFilename']=} chunkFilename chunk filename
* @property {Filename} filename filename
* @property {ChunkFilename=} chunkFilename chunk filename
* @property {boolean} ignoreOrder true when need to ignore order, otherwise false
* @property {string | ((linkTag: HTMLLinkElement) => void)=} insert a link insert place or a custom insert function
* @property {Record<string, string>=} attributes link attributes
Expand All @@ -70,9 +73,6 @@ const {
* @property {Record<string, string>=} attributes link attributes
*/

// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @typedef {any} TODO */

const pluginName = "mini-css-extract-plugin";
const pluginSymbol = Symbol(pluginName);

Expand All @@ -89,8 +89,9 @@ const CODE_GENERATION_RESULT = {
runtimeRequirements: new Set(),
};

/** @typedef {Module & { content: Buffer, media?: string, sourceMap?: Buffer, supports?: string, layer?: string, assets?: { [key: string]: TODO }, assetsInfo?: Map<string, AssetInfo> }} CssModule */
/** @typedef {{ context: string | null, identifier: string, identifierIndex: number, content: Buffer, sourceMap?: Buffer, media?: string, supports?: string, layer?: TODO, assetsInfo?: Map<string, AssetInfo>, assets?: { [key: string]: TODO }}} CssModuleDependency */
// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @typedef {{ context: string | null, identifier: string, identifierIndex: number, content: Buffer, sourceMap?: Buffer, media?: string, supports?: string, layer?: any, assetsInfo?: Map<string, AssetInfo>, assets?: { [key: string]: Source }}} CssModuleDependency */
/** @typedef {Module & { content: Buffer, media?: string, sourceMap?: Buffer, supports?: string, layer?: string, assets?: { [key: string]: Source }, assetsInfo?: Map<string, AssetInfo> }} CssModule */
/** @typedef {{ new(dependency: CssModuleDependency): CssModule }} CssModuleConstructor */
/** @typedef {Dependency & CssModuleDependency} CssDependency */
/** @typedef {Omit<LoaderDependency, "context">} CssDependencyOptions */
Expand Down Expand Up @@ -437,10 +438,8 @@ class MiniCssExtractPlugin {
this.sourceMap = sourceMap;
this.context = context;
/** @type {{ [key: string]: Source } | undefined}} */

this.assets = undefined;
/** @type {Map<string, AssetInfo> | undefined} */

this.assetsInfo = undefined;
}

Expand Down Expand Up @@ -486,7 +485,6 @@ class MiniCssExtractPlugin {
}
}

// @ts-expect-error
cssDependencyCache.set(webpack, CssDependency);

webpack.util.serialization.register(
Expand Down Expand Up @@ -525,7 +523,6 @@ class MiniCssExtractPlugin {
},
);

// @ts-expect-error
return CssDependency;
}

Expand Down Expand Up @@ -574,7 +571,6 @@ class MiniCssExtractPlugin {
filename: DEFAULT_FILENAME,
ignoreOrder: false,
// TODO remove in the next major release

experimentalUseImportModule: undefined,
runtime: true,
...options,
Expand Down Expand Up @@ -639,7 +635,7 @@ class MiniCssExtractPlugin {
) {
/** @type {Compiler["options"]["experiments"] & { executeModule?: boolean }} */

// @ts-expect-error
// @ts-expect-error TODO remove in the next major release
compiler.options.experiments.executeModule = true;
}

Expand Down Expand Up @@ -692,7 +688,7 @@ class MiniCssExtractPlugin {
class CssModuleFactory {
/**
* @param {{ dependencies: Dependency[] }} dependencies
* @param {(arg0?: Error, arg1?: TODO) => void} callback
* @param {(err?: null | Error, result?: CssModule) => void} callback
*/

create({ dependencies: [dependency] }, callback) {
Expand All @@ -705,6 +701,7 @@ class MiniCssExtractPlugin {

compilation.dependencyFactories.set(
CssDependency,
// @ts-expect-error TODO fix in the next major release and fix using `CssModuleFactory extends webpack.ModuleFactory`
new CssModuleFactory(),
);

Expand All @@ -722,7 +719,7 @@ class MiniCssExtractPlugin {
/**
* @param {ReturnType<Compilation["getRenderManifest"]>} result result
* @param {Parameters<Compilation["getRenderManifest"]>[0]} chunk chunk
* @returns {TODO} a rendered manifest
* @returns {ReturnType<Compilation["getRenderManifest"]>} a rendered manifest
*/
(result, { chunk }) => {
const { chunkGraph } = compilation;
Expand All @@ -731,7 +728,7 @@ class MiniCssExtractPlugin {
// We don't need hot update chunks for css
// We will use the real asset instead to update
if (chunk instanceof HotUpdateChunk) {
return;
return result;
}

const renderedModules =
Expand Down Expand Up @@ -774,6 +771,8 @@ class MiniCssExtractPlugin {
hash: chunk.contentHash[MODULE_TYPE],
});
}

return result;
},
);

Expand Down Expand Up @@ -1232,16 +1231,16 @@ class MiniCssExtractPlugin {
`${RuntimeGlobals.require}.miniCssF`,
/**
* @param {Chunk} referencedChunk a referenced chunk
* @returns {TODO} a template value
* @returns {ReturnType<import("webpack").runtime.GetChunkFilenameRuntimeModule["getFilenameForChunk"]>} a template value
*/
(referencedChunk) => {
if (!referencedChunk.contentHash[MODULE_TYPE]) {
return false;
}

return referencedChunk.canBeInitial()
? this.options.filename
: this.options.chunkFilename;
? /** @type {Filename} */ (this.options.filename)
: /** @type {ChunkFilename} */ (this.options.chunkFilename);
},
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers),
),
Expand Down
17 changes: 9 additions & 8 deletions src/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ const MiniCssExtractPlugin = require("./index");
/** @typedef {{[key: string]: string | Function }} Locals */

// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @typedef {any} TODO */
/** @typedef {any} EXPECTED_ANY */

/**
* @typedef {object} Dependency
* @property {string} identifier identifier
* @property {string | null} context context
* @property {Buffer=} content content
* @property {Buffer} content content
* @property {string=} media media
* @property {string=} supports supports
* @property {string=} layer layer
Expand Down Expand Up @@ -104,9 +104,9 @@ function pitch(request) {
const options = this.getOptions(/** @type {Schema} */ (schema));
const emit = typeof options.emit !== "undefined" ? options.emit : true;
const callback = this.async();
const optionsFromPlugin = /** @type {TODO} */ (this)[
MiniCssExtractPlugin.pluginSymbol
];
const optionsFromPlugin =
// @ts-expect-error
this[MiniCssExtractPlugin.pluginSymbol];

if (!optionsFromPlugin) {
callback(
Expand All @@ -121,7 +121,7 @@ function pitch(request) {
const { webpack } = /** @type {Compiler} */ (this._compiler);

/**
* @param {TODO} originalExports original exports
* @param {EXPECTED_ANY} originalExports original exports
* @param {Compilation=} compilation compilation
* @param {{ [name: string]: Source }=} assets assets
* @param {Map<string, AssetInfo>=} assetsInfo assets info
Expand Down Expand Up @@ -201,14 +201,15 @@ function pitch(request) {
locals = {};
}

/** @type {Locals} */ (locals)[key] = originalExports[key];
/** @type {Locals} */
(locals)[key] = originalExports[key];
}
}
} else {
locals = exports && exports.locals;
}

/** @type {Dependency[] | [null, TODO][]} */
/** @type {Dependency[] | [null, Record<string, string>][]} */
let dependencies;

if (!Array.isArray(exports)) {
Expand Down
Loading
Loading