From 30df92b7dcd86f22cef6254b1d2422bf94657f67 Mon Sep 17 00:00:00 2001 From: harpsealjs Date: Sun, 25 Oct 2026 18:44:47 +0800 Subject: [PATCH] fix: keep refresh hooks available after module execution --- client/intercept.js | 54 +++-- .../__snapshots__/web/0.snap.txt | 12 ++ .../__snapshots__/web/1.snap.txt | 158 ++++++++++++++ .../__snapshots__/web/2.snap.txt | 200 ++++++++++++++++++ test/hotCases/hook/useState_nested/app.jsx | 34 +++ test/hotCases/hook/useState_nested/index.jsx | 23 ++ .../hook/useState_nested/rspack.config.js | 58 +++++ 7 files changed, 521 insertions(+), 18 deletions(-) create mode 100644 test/hotCases/hook/useState_nested/__snapshots__/web/0.snap.txt create mode 100644 test/hotCases/hook/useState_nested/__snapshots__/web/1.snap.txt create mode 100644 test/hotCases/hook/useState_nested/__snapshots__/web/2.snap.txt create mode 100644 test/hotCases/hook/useState_nested/app.jsx create mode 100644 test/hotCases/hook/useState_nested/index.jsx create mode 100644 test/hotCases/hook/useState_nested/rspack.config.js diff --git a/client/intercept.js b/client/intercept.js index 47593a2..ef23d3b 100644 --- a/client/intercept.js +++ b/client/intercept.js @@ -8,27 +8,40 @@ * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE */ +var createRefreshSig = function () { + var status = 'begin'; + var savedType; + + return function (type, key, forceReset, getCustomHooks) { + if (!savedType) savedType = type; + status = self.__PREFRESH__.sign( + type || savedType, + key, + forceReset, + getCustomHooks, + status, + ); + return type; + }; +}; + +var noopRefreshReg = function () {}; + +// Components declared during render call $RefreshSig$ after their module +// factory has completed, so the hook must remain callable outside that scope. +if (typeof self.$RefreshSig$ !== 'function') { + self.$RefreshSig$ = createRefreshSig; +} +if (typeof self.$RefreshReg$ !== 'function') { + self.$RefreshReg$ = noopRefreshReg; +} + __webpack_require__.i.push(function (options) { var originalFactory = options.factory; options.factory = function (moduleObject, moduleExports, webpackRequire) { var prevRefreshReg = self.$RefreshReg$; var prevRefreshSig = self.$RefreshSig$; - self.$RefreshSig$ = function () { - var status = 'begin'; - var savedType; - - return function (type, key, forceReset, getCustomHooks) { - if (!savedType) savedType = type; - status = self.__PREFRESH__.sign( - type || savedType, - key, - forceReset, - getCustomHooks, - status, - ); - return type; - }; - }; + self.$RefreshSig$ = createRefreshSig; var reg = function (currentModuleId) { self.$RefreshReg$ = function (type, id) { self.__PREFRESH__.register(type, currentModuleId + ' ' + id); @@ -38,8 +51,13 @@ __webpack_require__.i.push(function (options) { try { originalFactory.call(this, moduleObject, moduleExports, webpackRequire); } finally { - self.$RefreshReg$ = prevRefreshReg; - self.$RefreshSig$ = prevRefreshSig; + // Restore the parent module hook, or detach registration at the root. + self.$RefreshReg$ = + typeof prevRefreshReg === 'function' ? prevRefreshReg : noopRefreshReg; + self.$RefreshSig$ = + typeof prevRefreshSig === 'function' + ? prevRefreshSig + : createRefreshSig; } }; }); diff --git a/test/hotCases/hook/useState_nested/__snapshots__/web/0.snap.txt b/test/hotCases/hook/useState_nested/__snapshots__/web/0.snap.txt new file mode 100644 index 0000000..b895aa7 --- /dev/null +++ b/test/hotCases/hook/useState_nested/__snapshots__/web/0.snap.txt @@ -0,0 +1,12 @@ +# Case useState_nested: Step 0 + +## Changed Files + + +## Asset Files +- Bundle: bundle.js + +## Manifest + + +## Update \ No newline at end of file diff --git a/test/hotCases/hook/useState_nested/__snapshots__/web/1.snap.txt b/test/hotCases/hook/useState_nested/__snapshots__/web/1.snap.txt new file mode 100644 index 0000000..08926fd --- /dev/null +++ b/test/hotCases/hook/useState_nested/__snapshots__/web/1.snap.txt @@ -0,0 +1,158 @@ +# Case useState_nested: Step 1 + +## Changed Files +- app.jsx + +## Asset Files +- Bundle: bundle.js +- Manifest: main.LAST_HASH.hot-update.json, size: 28 +- Update: main.LAST_HASH.hot-update.js, size: 4289 + +## Manifest + +### main.LAST_HASH.hot-update.json + +```json +{"c":["main"],"r":[],"m":[]} +``` + + +## Update + + +### main.LAST_HASH.hot-update.js + +#### Changed Modules +- ./app.jsx + +#### Changed Runtime Modules +- webpack/runtime/get_full_hash + +#### Changed Content +```js +"use strict"; +self["rspackHotUpdate"]("main", { +"./app.jsx"(module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +__webpack_require__.d(__webpack_exports__, { + App: () => (App) +}); +/* import */ var _swc_helpers_sliced_to_array__rspack_import_2 = __webpack_require__("/@swc/helpers/esm/_sliced_to_array.js"); +/* import */ var react_jsx_dev_runtime__rspack_import_0 = __webpack_require__("/preact/compat/jsx-dev-runtime.js"); +/* import */ var preact_hooks__rspack_import_1 = __webpack_require__("/preact/hooks/dist/hooks.module.js"); +/* module decorator */ module = __webpack_require__.hmd(module); +/* provided dependency */ var __prefresh_utils__ = __webpack_require__("../../../../../../../client/prefresh.js")["default"]; + + + +function App() { + var _this = this; + var _s = $RefreshSig$(); + var Nested = function Nested() { + _s(); + var _useState = (0,_swc_helpers_sliced_to_array__rspack_import_2._)((0,preact_hooks__rspack_import_1.useState)('content 2'), 1), text = _useState[0]; + return /*#__PURE__*/ (0,react_jsx_dev_runtime__rspack_import_0.jsxDEV)("span", { + children: text + }, void 0, false, { + fileName: "/test/js/temp/hot-snapshot/hotSnapshotCases-hotCases/hook/useState_nested/app.jsx", + lineNumber: 6, + columnNumber: 12 + }, _this); + }; + _s(Nested, "X+F/KlmfVDgKs4Hn0tEJDyERets="); + return /*#__PURE__*/ (0,react_jsx_dev_runtime__rspack_import_0.jsxDEV)(Nested, {}, void 0, false, { + fileName: "/test/js/temp/hot-snapshot/hotSnapshotCases-hotCases/hook/useState_nested/app.jsx", + lineNumber: 9, + columnNumber: 10 + }, this); +} +_c = App; +var _c; +$RefreshReg$(_c, "App"); + +/** + * The following code is modified based on + * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js + * + * MIT Licensed + * Author JoviDeCroock + * Copyright (c) 2021-Present Preact Team + * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE + */ + +const isPrefreshComponent = __prefresh_utils__.shouldBind(module); + +// `@vanilla-extract/webpack` does some custom preprocessing where +// `module.hot` is partially replaced. This leads to our injected +// code being executed although it shouldn't be: +// +// Intermediate result: +// +// if (true) { // <- inlined by intermediate compile step +// const previousHotModuleExports = module.hot.data && ... +// // Crash happens here ---^ +// +// It crashes at that line because some intermediate compiler isn't +// running in hot mode, but the overall guard condition was compiled +// down to being truthy. By moving `module.hot` outside of the +// condition of the if-statement, it will be left as is. +const moduleHot = module.hot; + +if (moduleHot) { + const currentExports = __prefresh_utils__.getExports(module); + const previousHotModuleExports = + moduleHot.data && moduleHot.data.moduleExports; + + __prefresh_utils__.registerExports(currentExports, module.id); + + if (isPrefreshComponent) { + if (previousHotModuleExports) { + try { + __prefresh_utils__.flush(); + if ( + typeof __prefresh_errors__ !== 'undefined' && + __prefresh_errors__ && + __prefresh_errors__.clearRuntimeErrors + ) { + __prefresh_errors__.clearRuntimeErrors(); + } + } catch (e) { + // Only available in newer webpack versions. + if (moduleHot.invalidate) { + moduleHot.invalidate(); + } else { + self.location.reload(); + } + } + } + + moduleHot.dispose(data => { + data.moduleExports = __prefresh_utils__.getExports(module); + }); + + moduleHot.accept(function errorRecovery(error) { + if ( + typeof __prefresh_errors__ !== 'undefined' && + __prefresh_errors__ && + __prefresh_errors__.handleRuntimeError + ) { + __prefresh_errors__.handleRuntimeError(error); + } + + __webpack_require__.c[module.id].hot.accept(errorRecovery); + }); + } +} + + +}, + +},function(__webpack_require__) { +// webpack/runtime/get_full_hash +(() => { +__webpack_require__.h = () => ("CURRENT_HASH") +})(); + +} +); +``` \ No newline at end of file diff --git a/test/hotCases/hook/useState_nested/__snapshots__/web/2.snap.txt b/test/hotCases/hook/useState_nested/__snapshots__/web/2.snap.txt new file mode 100644 index 0000000..905e9e9 --- /dev/null +++ b/test/hotCases/hook/useState_nested/__snapshots__/web/2.snap.txt @@ -0,0 +1,200 @@ +# Case useState_nested: Step 2 + +## Changed Files +- app.jsx + +## Asset Files +- Bundle: bundle.js +- Manifest: main.LAST_HASH.hot-update.json, size: 28 +- Update: main.LAST_HASH.hot-update.js, size: 4289 + +## Manifest + +### main.LAST_HASH.hot-update.json + +```json +{"c":["main"],"r":[],"m":[]} +``` + + +## Update + + +### main.LAST_HASH.hot-update.js + +#### Changed Modules +- ./app.jsx + +#### Changed Runtime Modules +- webpack/runtime/get_full_hash + +#### Changed Content +```js +"use strict"; +self["rspackHotUpdate"]("main", { +"./app.jsx"(module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +__webpack_require__.d(__webpack_exports__, { + App: () => (App) +}); +/* import */ var _swc_helpers_sliced_to_array__rspack_import_2 = __webpack_require__("/@swc/helpers/esm/_sliced_to_array.js"); +/* import */ var react_jsx_dev_runtime__rspack_import_0 = __webpack_require__("/preact/compat/jsx-dev-runtime.js"); +/* import */ var preact_hooks__rspack_import_1 = __webpack_require__("/preact/hooks/dist/hooks.module.js"); +/* module decorator */ module = __webpack_require__.hmd(module); +/* provided dependency */ var __prefresh_utils__ = __webpack_require__("../../../../../../../client/prefresh.js")["default"]; + + + +function App() { + var _this = this; + var _s = $RefreshSig$(); + var Nested = function Nested() { + _s(); + var _useState = (0,_swc_helpers_sliced_to_array__rspack_import_2._)((0,preact_hooks__rspack_import_1.useState)('content 3'), 1), text = _useState[0]; + return /*#__PURE__*/ (0,react_jsx_dev_runtime__rspack_import_0.jsxDEV)("span", { + children: text + }, void 0, false, { + fileName: "/test/js/temp/hot-snapshot/hotSnapshotCases-hotCases/hook/useState_nested/app.jsx", + lineNumber: 6, + columnNumber: 12 + }, _this); + }; + _s(Nested, "jBBe1p3bxMN2LgzqadjvgynDfkk="); + return /*#__PURE__*/ (0,react_jsx_dev_runtime__rspack_import_0.jsxDEV)(Nested, {}, void 0, false, { + fileName: "/test/js/temp/hot-snapshot/hotSnapshotCases-hotCases/hook/useState_nested/app.jsx", + lineNumber: 9, + columnNumber: 10 + }, this); +} +_c = App; +var _c; +$RefreshReg$(_c, "App"); + +/** + * The following code is modified based on + * //https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/packages/webpack/src/loader/runtime.js + * + * MIT Licensed + * Author JoviDeCroock + * Copyright (c) 2021-Present Preact Team + * https://github.com/preactjs/prefresh/blob/018f5cc907629b82ffb201c32e948efe4b40098a/LICENSE + */ + +const isPrefreshComponent = __prefresh_utils__.shouldBind(module); + +// `@vanilla-extract/webpack` does some custom preprocessing where +// `module.hot` is partially replaced. This leads to our injected +// code being executed although it shouldn't be: +// +// Intermediate result: +// +// if (true) { // <- inlined by intermediate compile step +// const previousHotModuleExports = module.hot.data && ... +// // Crash happens here ---^ +// +// It crashes at that line because some intermediate compiler isn't +// running in hot mode, but the overall guard condition was compiled +// down to being truthy. By moving `module.hot` outside of the +// condition of the if-statement, it will be left as is. +const moduleHot = module.hot; + +if (moduleHot) { + const currentExports = __prefresh_utils__.getExports(module); + const previousHotModuleExports = + moduleHot.data && moduleHot.data.moduleExports; + + __prefresh_utils__.registerExports(currentExports, module.id); + + if (isPrefreshComponent) { + if (previousHotModuleExports) { + try { + __prefresh_utils__.flush(); + if ( + typeof __prefresh_errors__ !== 'undefined' && + __prefresh_errors__ && + __prefresh_errors__.clearRuntimeErrors + ) { + __prefresh_errors__.clearRuntimeErrors(); + } + } catch (e) { + // Only available in newer webpack versions. + if (moduleHot.invalidate) { + moduleHot.invalidate(); + } else { + self.location.reload(); + } + } + } + + moduleHot.dispose(data => { + data.moduleExports = __prefresh_utils__.getExports(module); + }); + + moduleHot.accept(function errorRecovery(error) { + if ( + typeof __prefresh_errors__ !== 'undefined' && + __prefresh_errors__ && + __prefresh_errors__.handleRuntimeError + ) { + __prefresh_errors__.handleRuntimeError(error); + } + + __webpack_require__.c[module.id].hot.accept(errorRecovery); + }); + } +} + + +}, + +},function(__webpack_require__) { +// webpack/runtime/get_full_hash +(() => { +__webpack_require__.h = () => ("CURRENT_HASH") +})(); + +} +); +``` + + + + +## Runtime +### Status + +```txt +check => prepare => dispose => apply => idle +``` + + + +### JavaScript + +#### Outdated + +Outdated Modules: +- ./app.jsx + + +Outdated Dependencies: +```json +{} +``` + +#### Updated + +Updated Modules: +- ./app.jsx + +Updated Runtime: +- `__webpack_require__.h` + + +#### Callback + +Accepted Callback: + + +Disposed Callback: +- ./app.jsx \ No newline at end of file diff --git a/test/hotCases/hook/useState_nested/app.jsx b/test/hotCases/hook/useState_nested/app.jsx new file mode 100644 index 0000000..e96dc53 --- /dev/null +++ b/test/hotCases/hook/useState_nested/app.jsx @@ -0,0 +1,34 @@ +import { useState } from 'preact/hooks'; + +export function App() { + const Nested = () => { + const [text] = useState('content 1'); + return {text}; + }; + + return ; +} + +--- +import { useState } from 'preact/hooks'; + +export function App() { + const Nested = () => { + const [text] = useState('content 2'); + return {text}; + }; + + return ; +} + +--- +import { useState } from 'preact/hooks'; + +export function App() { + const Nested = () => { + const [text] = useState('content 3'); + return {text}; + }; + + return ; +} diff --git a/test/hotCases/hook/useState_nested/index.jsx b/test/hotCases/hook/useState_nested/index.jsx new file mode 100644 index 0000000..b9dbd74 --- /dev/null +++ b/test/hotCases/hook/useState_nested/index.jsx @@ -0,0 +1,23 @@ +import React from 'react'; +import ReactDOM from 'react-dom/client'; +import { App } from './app'; + +const container = document.createElement('div'); +container.id = 'root'; +document.body.appendChild(container); +const root = ReactDOM.createRoot(container); +root.render(); + +it('should refresh components declared during render', async () => { + expect(container.querySelector('span').textContent).toBe('content 1'); + + await NEXT_HMR(); + expect(container.querySelector('span').textContent).toBe('content 2'); + + await NEXT_HMR(); + expect(container.querySelector('span').textContent).toBe('content 3'); +}); + +if (module.hot) { + module.hot.accept('./app'); +} diff --git a/test/hotCases/hook/useState_nested/rspack.config.js b/test/hotCases/hook/useState_nested/rspack.config.js new file mode 100644 index 0000000..b80b5ef --- /dev/null +++ b/test/hotCases/hook/useState_nested/rspack.config.js @@ -0,0 +1,58 @@ +const { PreactRefreshRspackPlugin } = require('../../../../dist/index.js'); + +/** @type {import('@rspack/core').Configuration} */ +module.exports = { + context: __dirname, + entry: './index.jsx', + resolve: { + extensions: ['...', '.ts', '.tsx', '.jsx'], + alias: { + react: 'preact/compat', + 'react-dom/test-utils': 'preact/test-utils', + 'react-dom': 'preact/compat', // Must be below test-utils + 'react/jsx-runtime': 'preact/jsx-runtime', + }, + }, + module: { + rules: [ + { + test: /\.jsx?$/, + exclude: [/node_modules/], + use: { + loader: 'builtin:swc-loader', + options: { + jsc: { + experimental: { + plugins: [ + [ + '@swc/plugin-prefresh', // enable prefresh specific transformation + {}, + ], + ], + }, + parser: { + syntax: 'ecmascript', + jsx: true, + }, + externalHelpers: true, + preserveAllComments: false, + transform: { + react: { + runtime: 'automatic', + pragma: 'h', + pragmaFrag: 'Fragment', + throwIfNamespace: true, + useBuiltins: false, + development: true, + refresh: true, // enable react hooks hmr compatiblity + }, + }, + }, + }, + }, + type: 'javascript/auto', + }, + ], + }, + plugins: [new PreactRefreshRspackPlugin()], +};