Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@rspack/plugin-react-refresh

Package Overview
Dependencies
Maintainers
0
Versions
558
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rspack/plugin-react-refresh - npm Package Compare versions

Comparing version 1.0.0-beta.3 to 1.0.0-beta.4

16

client/errorOverlayEntry.js

@@ -97,6 +97,8 @@ /* global __react_refresh_error_overlay__, __react_refresh_socket__, __resourceQuery */

});
events.handleUnhandledRejection(function handleUnhandledPromiseRejection(error) {
hasRuntimeErrors = true;
__react_refresh_error_overlay__.handleRuntimeError(error);
});
events.handleUnhandledRejection(
function handleUnhandledPromiseRejection(error) {
hasRuntimeErrors = true;
__react_refresh_error_overlay__.handleRuntimeError(error);
},
);

@@ -106,5 +108,5 @@ // Mark overlay as injected to prevent double-injection

}
};
setupOverlay()
}
setupOverlay();
}
}
}

@@ -36,4 +36,9 @@ const ansiHTML = require('../../utils/ansi-html.js');

stackContainer.innerHTML = entities.decode(
ansiHTML(entities.encode(errorParts.join('\n'), { level: 'html5', mode: 'nonAscii' })),
{ level: 'html5' }
ansiHTML(
entities.encode(errorParts.join('\n'), {
level: 'html5',
mode: 'nonAscii',
}),
),
{ level: 'html5' },
);

@@ -40,0 +45,0 @@ stackContainer.style.fontFamily = [

@@ -26,4 +26,6 @@ const Spacer = require('./Spacer.js');

pageHeaderContainer.style.padding = '1rem 1.5rem';
pageHeaderContainer.style.paddingLeft = 'max(1.5rem, env(safe-area-inset-left))';
pageHeaderContainer.style.paddingRight = 'max(1.5rem, env(safe-area-inset-right))';
pageHeaderContainer.style.paddingLeft =
'max(1.5rem, env(safe-area-inset-left))';
pageHeaderContainer.style.paddingRight =
'max(1.5rem, env(safe-area-inset-right))';
pageHeaderContainer.style.position = 'fixed';

@@ -30,0 +32,0 @@ pageHeaderContainer.style.top = props.topOffset || '0';

@@ -19,3 +19,4 @@ const Spacer = require('./Spacer.js');

const header = document.createElement('div');
header.innerText = 'Error ' + (props.currentErrorIndex + 1) + ' of ' + props.totalErrors;
header.innerText =
'Error ' + (props.currentErrorIndex + 1) + ' of ' + props.totalErrors;
header.style.backgroundColor = '#' + theme.red;

@@ -22,0 +23,0 @@ header.style.color = '#' + theme.white;

@@ -43,3 +43,4 @@ const ErrorStackParser = require('error-stack-parser');

const functionName = document.createElement('code');
functionName.innerHTML = ' ' + currentStack.functionName || '(anonymous function)';
functionName.innerHTML =
' ' + currentStack.functionName || '(anonymous function)';
functionName.style.color = '#' + theme.yellow;

@@ -46,0 +47,0 @@ functionName.style.fontFamily = [

@@ -326,3 +326,6 @@ /**

function isWebpackCompileError(error) {
return /Module [A-z ]+\(from/.test(error.message) || /Cannot find module/.test(error.message);
return (
/Module [A-z ]+\(from/.test(error.message) ||
/Cannot find module/.test(error.message)
);
}

@@ -337,3 +340,7 @@

function handleRuntimeError(error) {
if (error && !isWebpackCompileError(error) && currentRuntimeErrors.indexOf(error) === -1) {
if (
error &&
!isWebpackCompileError(error) &&
currentRuntimeErrors.indexOf(error) === -1
) {
currentRuntimeErrors = currentRuntimeErrors.concat(error);

@@ -350,2 +357,2 @@ }

showRuntimeErrors: showRuntimeErrors,
});
});

@@ -62,3 +62,3 @@ /**

element.childNodes,
typeof skip !== 'undefined' ? skip : 0
typeof skip !== 'undefined' ? skip : 0,
);

@@ -65,0 +65,0 @@

// Thanks https://github.com/pmmmwh/react-refresh-webpack-plugin
const RefreshUtils = require("./refreshUtils");
const RefreshRuntime = require("react-refresh/runtime");
const RefreshUtils = require('./refreshUtils');
const RefreshRuntime = require('react-refresh/runtime');
// Port from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/loader/utils/getRefreshModuleRuntime.js#L29
function refresh(moduleId, webpackHot) {
const currentExports = RefreshUtils.getModuleExports(moduleId);
const fn = exports => {
RefreshUtils.executeRuntime(exports, moduleId, webpackHot);
};
if (typeof Promise !== "undefined" && currentExports instanceof Promise) {
currentExports.then(fn);
} else {
fn(currentExports);
}
const currentExports = RefreshUtils.getModuleExports(moduleId);
const fn = (exports) => {
RefreshUtils.executeRuntime(exports, moduleId, webpackHot);
};
if (typeof Promise !== 'undefined' && currentExports instanceof Promise) {
currentExports.then(fn);
} else {
fn(currentExports);
}
}
module.exports = {
refresh,
register: RefreshRuntime.register,
createSignatureFunctionForTransform:
RefreshRuntime.createSignatureFunctionForTransform
refresh,
register: RefreshRuntime.register,
createSignatureFunctionForTransform:
RefreshRuntime.createSignatureFunctionForTransform,
};

@@ -11,51 +11,51 @@ /**

var RefreshRuntime = require("react-refresh/runtime");
var RefreshRuntime = require('react-refresh/runtime');
var safeThis = (function () {
// copied from core-js-pure/features/global-this
"use strict";
// copied from core-js-pure/features/global-this
'use strict';
var check = function (it) {
return it && it.Math == Math && it;
};
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
// eslint-disable-next-line es/no-global-this -- safe
return (
check(typeof globalThis == "object" && globalThis) ||
check(typeof window == "object" && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == "object" && self) ||
check(typeof __webpack_require__.g == "object" && __webpack_require__.g) ||
// eslint-disable-next-line no-new-func -- fallback
(function () {
return this;
})() ||
this ||
Function("return this")()
);
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
// eslint-disable-next-line es/no-global-this -- safe
return (
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == 'object' && self) ||
check(typeof __webpack_require__.g == 'object' && __webpack_require__.g) ||
// eslint-disable-next-line no-new-func -- fallback
(function () {
return this;
})() ||
this ||
Function('return this')()
);
})();
if (process.env.NODE_ENV !== "production") {
if (typeof safeThis !== "undefined") {
var $RefreshInjected$ = "__reactRefreshInjected";
// Namespace the injected flag (if necessary) for monorepo compatibility
if (
typeof __react_refresh_library__ !== "undefined" &&
__react_refresh_library__
) {
$RefreshInjected$ += "_" + __react_refresh_library__;
}
if (process.env.NODE_ENV !== 'production') {
if (typeof safeThis !== 'undefined') {
var $RefreshInjected$ = '__reactRefreshInjected';
// Namespace the injected flag (if necessary) for monorepo compatibility
if (
typeof __react_refresh_library__ !== 'undefined' &&
__react_refresh_library__
) {
$RefreshInjected$ += '_' + __react_refresh_library__;
}
// Only inject the runtime if it hasn't been injected
if (!safeThis[$RefreshInjected$]) {
RefreshRuntime.injectIntoGlobalHook(safeThis);
// Only inject the runtime if it hasn't been injected
if (!safeThis[$RefreshInjected$]) {
RefreshRuntime.injectIntoGlobalHook(safeThis);
// Empty implementation to avoid "ReferenceError: variable is not defined" in module which didn't pass builtin:react-refresh-loader
safeThis.$RefreshSig$ = () => type => type;
safeThis.$RefreshReg$ = () => {};
// Empty implementation to avoid "ReferenceError: variable is not defined" in module which didn't pass builtin:react-refresh-loader
safeThis.$RefreshSig$ = () => (type) => type;
safeThis.$RefreshReg$ = () => {};
// Mark the runtime as injected to prevent double-injection
safeThis[$RefreshInjected$] = true;
}
}
// Mark the runtime as injected to prevent double-injection
safeThis[$RefreshInjected$] = true;
}
}
}

@@ -12,3 +12,3 @@ /**

/* global __webpack_require__ */
var Refresh = require("react-refresh/runtime");
var Refresh = require('react-refresh/runtime');

@@ -21,28 +21,28 @@ /**

function getModuleExports(moduleId) {
if (typeof moduleId === "undefined") {
// `moduleId` is unavailable, which indicates that this module is not in the cache,
// which means we won't be able to capture any exports,
// and thus they cannot be refreshed safely.
// These are likely runtime or dynamically generated modules.
return {};
}
if (typeof moduleId === 'undefined') {
// `moduleId` is unavailable, which indicates that this module is not in the cache,
// which means we won't be able to capture any exports,
// and thus they cannot be refreshed safely.
// These are likely runtime or dynamically generated modules.
return {};
}
var maybeModule = __webpack_require__.c[moduleId];
if (typeof maybeModule === "undefined") {
// `moduleId` is available but the module in cache is unavailable,
// which indicates the module is somehow corrupted (e.g. broken Webpacak `module` globals).
// We will warn the user (as this is likely a mistake) and assume they cannot be refreshed.
console.warn(
"[React Refresh] Failed to get exports for module: " + moduleId + "."
);
return {};
}
var maybeModule = __webpack_require__.c[moduleId];
if (typeof maybeModule === 'undefined') {
// `moduleId` is available but the module in cache is unavailable,
// which indicates the module is somehow corrupted (e.g. broken Webpacak `module` globals).
// We will warn the user (as this is likely a mistake) and assume they cannot be refreshed.
console.warn(
'[React Refresh] Failed to get exports for module: ' + moduleId + '.',
);
return {};
}
var exportsOrPromise = maybeModule.exports;
if (typeof Promise !== "undefined" && exportsOrPromise instanceof Promise) {
return exportsOrPromise.then(function (exports) {
return exports;
});
}
return exportsOrPromise;
var exportsOrPromise = maybeModule.exports;
if (typeof Promise !== 'undefined' && exportsOrPromise instanceof Promise) {
return exportsOrPromise.then(function (exports) {
return exports;
});
}
return exportsOrPromise;
}

@@ -59,20 +59,20 @@

function getReactRefreshBoundarySignature(moduleExports) {
var signature = [];
signature.push(Refresh.getFamilyByType(moduleExports));
var signature = [];
signature.push(Refresh.getFamilyByType(moduleExports));
if (moduleExports == null || typeof moduleExports !== "object") {
// Exit if we can't iterate over exports.
return signature;
}
if (moduleExports == null || typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
return signature;
}
for (var key in moduleExports) {
if (key === "__esModule") {
continue;
}
for (var key in moduleExports) {
if (key === '__esModule') {
continue;
}
signature.push(key);
signature.push(Refresh.getFamilyByType(moduleExports[key]));
}
signature.push(key);
signature.push(Refresh.getFamilyByType(moduleExports[key]));
}
return signature;
return signature;
}

@@ -85,24 +85,24 @@

function createDebounceUpdate() {
/**
* A cached setTimeout handler.
* @type {number | undefined}
*/
var refreshTimeout;
/**
* A cached setTimeout handler.
* @type {number | undefined}
*/
var refreshTimeout;
/**
* Performs react refresh on a delay and clears the error overlay.
* @param {function(): void} callback
* @returns {void}
*/
function enqueueUpdate(callback) {
if (typeof refreshTimeout === "undefined") {
refreshTimeout = setTimeout(function () {
refreshTimeout = undefined;
Refresh.performReactRefresh();
callback();
}, 30);
}
}
/**
* Performs react refresh on a delay and clears the error overlay.
* @param {function(): void} callback
* @returns {void}
*/
function enqueueUpdate(callback) {
if (typeof refreshTimeout === 'undefined') {
refreshTimeout = setTimeout(function () {
refreshTimeout = undefined;
Refresh.performReactRefresh();
callback();
}, 30);
}
}
return enqueueUpdate;
return enqueueUpdate;
}

@@ -118,35 +118,35 @@

function isReactRefreshBoundary(moduleExports) {
if (Refresh.isLikelyComponentType(moduleExports)) {
return true;
}
if (
moduleExports === undefined ||
moduleExports === null ||
typeof moduleExports !== "object"
) {
// Exit if we can't iterate over exports.
return false;
}
if (Refresh.isLikelyComponentType(moduleExports)) {
return true;
}
if (
moduleExports === undefined ||
moduleExports === null ||
typeof moduleExports !== 'object'
) {
// Exit if we can't iterate over exports.
return false;
}
var hasExports = false;
var areAllExportsComponents = true;
for (var key in moduleExports) {
hasExports = true;
var hasExports = false;
var areAllExportsComponents = true;
for (var key in moduleExports) {
hasExports = true;
// This is the ES Module indicator flag
if (key === "__esModule") {
continue;
}
// This is the ES Module indicator flag
if (key === '__esModule') {
continue;
}
// We can (and have to) safely execute getters here,
// as Webpack manually assigns harmony exports to getters,
// without any side-effects attached.
// Ref: https://github.com/webpack/webpack/blob/b93048643fe74de2a6931755911da1212df55897/lib/MainTemplate.js#L281
var exportValue = moduleExports[key];
if (!Refresh.isLikelyComponentType(exportValue)) {
areAllExportsComponents = false;
}
}
// We can (and have to) safely execute getters here,
// as Webpack manually assigns harmony exports to getters,
// without any side-effects attached.
// Ref: https://github.com/webpack/webpack/blob/b93048643fe74de2a6931755911da1212df55897/lib/MainTemplate.js#L281
var exportValue = moduleExports[key];
if (!Refresh.isLikelyComponentType(exportValue)) {
areAllExportsComponents = false;
}
}
return hasExports && areAllExportsComponents;
return hasExports && areAllExportsComponents;
}

@@ -163,28 +163,28 @@

function registerExportsForReactRefresh(moduleExports, moduleId) {
if (Refresh.isLikelyComponentType(moduleExports)) {
// Register module.exports if it is likely a component
Refresh.register(moduleExports, moduleId + " %exports%");
}
if (Refresh.isLikelyComponentType(moduleExports)) {
// Register module.exports if it is likely a component
Refresh.register(moduleExports, moduleId + ' %exports%');
}
if (
moduleExports === undefined ||
moduleExports === null ||
typeof moduleExports !== "object"
) {
// Exit if we can't iterate over the exports.
return;
}
if (
moduleExports === undefined ||
moduleExports === null ||
typeof moduleExports !== 'object'
) {
// Exit if we can't iterate over the exports.
return;
}
for (var key in moduleExports) {
// Skip registering the ES Module indicator
if (key === "__esModule") {
continue;
}
for (var key in moduleExports) {
// Skip registering the ES Module indicator
if (key === '__esModule') {
continue;
}
var exportValue = moduleExports[key];
if (Refresh.isLikelyComponentType(exportValue)) {
var typeID = moduleId + " %exports% " + key;
Refresh.register(exportValue, typeID);
}
}
var exportValue = moduleExports[key];
if (Refresh.isLikelyComponentType(exportValue)) {
var typeID = moduleId + ' %exports% ' + key;
Refresh.register(exportValue, typeID);
}
}
}

@@ -201,16 +201,16 @@

function shouldInvalidateReactRefreshBoundary(prevExports, nextExports) {
var prevSignature = getReactRefreshBoundarySignature(prevExports);
var nextSignature = getReactRefreshBoundarySignature(nextExports);
var prevSignature = getReactRefreshBoundarySignature(prevExports);
var nextSignature = getReactRefreshBoundarySignature(nextExports);
if (prevSignature.length !== nextSignature.length) {
return true;
}
if (prevSignature.length !== nextSignature.length) {
return true;
}
for (var i = 0; i < nextSignature.length; i += 1) {
if (prevSignature[i] !== nextSignature[i]) {
return true;
}
}
for (var i = 0; i < nextSignature.length; i += 1) {
if (prevSignature[i] !== nextSignature[i]) {
return true;
}
}
return false;
return false;
}

@@ -220,86 +220,86 @@

function executeRuntime(
moduleExports,
moduleId,
webpackHot,
refreshOverlay,
isTest
moduleExports,
moduleId,
webpackHot,
refreshOverlay,
isTest,
) {
registerExportsForReactRefresh(moduleExports, moduleId);
registerExportsForReactRefresh(moduleExports, moduleId);
if (webpackHot) {
var isHotUpdate = !!webpackHot.data;
var prevExports;
if (isHotUpdate) {
prevExports = webpackHot.data.prevExports;
}
if (webpackHot) {
var isHotUpdate = !!webpackHot.data;
var prevExports;
if (isHotUpdate) {
prevExports = webpackHot.data.prevExports;
}
if (isReactRefreshBoundary(moduleExports)) {
webpackHot.dispose(
/**
* A callback to performs a full refresh if React has unrecoverable errors,
* and also caches the to-be-disposed module.
* @param {*} data A hot module data object from Webpack HMR.
* @returns {void}
*/
function hotDisposeCallback(data) {
// We have to mutate the data object to get data registered and cached
data.prevExports = moduleExports;
}
);
webpackHot.accept(
/**
* An error handler to allow self-recovering behaviours.
* @param {Error} error An error occurred during evaluation of a module.
* @returns {void}
*/
function hotErrorHandler(error) {
if (typeof refreshOverlay !== "undefined" && refreshOverlay) {
refreshOverlay.handleRuntimeError(error);
}
if (isReactRefreshBoundary(moduleExports)) {
webpackHot.dispose(
/**
* A callback to performs a full refresh if React has unrecoverable errors,
* and also caches the to-be-disposed module.
* @param {*} data A hot module data object from Webpack HMR.
* @returns {void}
*/
function hotDisposeCallback(data) {
// We have to mutate the data object to get data registered and cached
data.prevExports = moduleExports;
},
);
webpackHot.accept(
/**
* An error handler to allow self-recovering behaviours.
* @param {Error} error An error occurred during evaluation of a module.
* @returns {void}
*/
function hotErrorHandler(error) {
if (typeof refreshOverlay !== 'undefined' && refreshOverlay) {
refreshOverlay.handleRuntimeError(error);
}
if (typeof isTest !== "undefined" && isTest) {
if (window.onHotAcceptError) {
window.onHotAcceptError(error.message);
}
}
if (typeof isTest !== 'undefined' && isTest) {
if (window.onHotAcceptError) {
window.onHotAcceptError(error.message);
}
}
__webpack_require__.c[moduleId].hot.accept(hotErrorHandler);
}
);
__webpack_require__.c[moduleId].hot.accept(hotErrorHandler);
},
);
if (isHotUpdate) {
if (
isReactRefreshBoundary(prevExports) &&
shouldInvalidateReactRefreshBoundary(prevExports, moduleExports)
) {
webpackHot.invalidate();
} else {
enqueueUpdate(
/**
* A function to dismiss the error overlay after performing React refresh.
* @returns {void}
*/
function updateCallback() {
if (typeof refreshOverlay !== "undefined" && refreshOverlay) {
refreshOverlay.clearRuntimeErrors();
}
}
);
}
}
} else {
if (isHotUpdate && typeof prevExports !== "undefined") {
webpackHot.invalidate();
}
}
}
if (isHotUpdate) {
if (
isReactRefreshBoundary(prevExports) &&
shouldInvalidateReactRefreshBoundary(prevExports, moduleExports)
) {
webpackHot.invalidate();
} else {
enqueueUpdate(
/**
* A function to dismiss the error overlay after performing React refresh.
* @returns {void}
*/
function updateCallback() {
if (typeof refreshOverlay !== 'undefined' && refreshOverlay) {
refreshOverlay.clearRuntimeErrors();
}
},
);
}
}
} else {
if (isHotUpdate && typeof prevExports !== 'undefined') {
webpackHot.invalidate();
}
}
}
}
module.exports = Object.freeze({
enqueueUpdate: enqueueUpdate,
executeRuntime: executeRuntime,
getModuleExports: getModuleExports,
isReactRefreshBoundary: isReactRefreshBoundary,
shouldInvalidateReactRefreshBoundary: shouldInvalidateReactRefreshBoundary,
registerExportsForReactRefresh: registerExportsForReactRefresh
enqueueUpdate: enqueueUpdate,
executeRuntime: executeRuntime,
getModuleExports: getModuleExports,
isReactRefreshBoundary: isReactRefreshBoundary,
shouldInvalidateReactRefreshBoundary: shouldInvalidateReactRefreshBoundary,
registerExportsForReactRefresh: registerExportsForReactRefresh,
});

@@ -14,3 +14,3 @@ /* eslint-disable */

*/
"use strict";
'use strict';

@@ -24,39 +24,39 @@ module.exports = ansiHTML;

var _defColors = {
reset: ["fff", "000"], // [FOREGROUND_COLOR, BACKGROUND_COLOR]
black: "000",
red: "ff0000",
green: "209805",
yellow: "e8bf03",
blue: "0000ff",
magenta: "ff00ff",
cyan: "00ffee",
lightgrey: "f0f0f0",
darkgrey: "888"
reset: ['fff', '000'], // [FOREGROUND_COLOR, BACKGROUND_COLOR]
black: '000',
red: 'ff0000',
green: '209805',
yellow: 'e8bf03',
blue: '0000ff',
magenta: 'ff00ff',
cyan: '00ffee',
lightgrey: 'f0f0f0',
darkgrey: '888',
};
var _styles = {
30: "black",
31: "red",
32: "green",
33: "yellow",
34: "blue",
35: "magenta",
36: "cyan",
37: "lightgrey"
30: 'black',
31: 'red',
32: 'green',
33: 'yellow',
34: 'blue',
35: 'magenta',
36: 'cyan',
37: 'lightgrey',
};
var _colorMode = {
2: "rgb"
2: 'rgb',
};
var _openTags = {
1: "font-weight:bold", // bold
2: "opacity:0.5", // dim
3: "<i>", // italic
4: "<u>", // underscore
8: "display:none", // hidden
9: "<del>", // delete
1: 'font-weight:bold', // bold
2: 'opacity:0.5', // dim
3: '<i>', // italic
4: '<u>', // underscore
8: 'display:none', // hidden
9: '<del>', // delete
38: function (match) {
// color
var mode = _colorMode[match[0]];
if (mode === "rgb") {
if (mode === 'rgb') {
var r, g, b;

@@ -67,3 +67,3 @@ r = match[1];

match.advance(4);
return "color: rgb(" + r + "," + g + "," + b + ")";
return 'color: rgb(' + r + ',' + g + ',' + b + ')';
}

@@ -74,3 +74,3 @@ },

var mode = _colorMode[match[0]];
if (mode === "rgb") {
if (mode === 'rgb') {
var r, g, b;

@@ -81,11 +81,11 @@ r = match[1];

match.advance(4);
return "background-color: rgb(" + r + "," + g + "," + b + ")";
return 'background-color: rgb(' + r + ',' + g + ',' + b + ')';
}
}
},
};
var _openTagToCloseTag = {
3: "23",
4: "24",
9: "29"
3: '23',
4: '24',
9: '29',
};

@@ -95,6 +95,6 @@

0: function (ansiCodes) {
if (!ansiCodes) return "</span>";
if (!ansiCodes.length) return "";
if (!ansiCodes) return '</span>';
if (!ansiCodes.length) return '';
var code,
ret = "";
ret = '';
while ((code = ansiCodes.pop())) {

@@ -106,13 +106,13 @@ var closeTag = _openTagToCloseTag[code];

}
ret += "</span>";
ret += '</span>';
}
return ret;
},
23: "</i>", // reset italic
24: "</u>", // reset underscore
29: "</del>" // reset delete
23: '</i>', // reset italic
24: '</u>', // reset underscore
29: '</del>', // reset delete
};
[21, 22, 27, 28, 39, 49].forEach(function (n) {
_closeTags[n] = "</span>";
_closeTags[n] = '</span>';
});

@@ -127,3 +127,3 @@

if (seq === null || seq === undefined) return null;
if (seq.startsWith(";")) {
if (seq.startsWith(';')) {
return seq.slice(1);

@@ -152,9 +152,9 @@ }

var match = m.match(/(;?\d+)/g).map(normalizeSeq);
Object.defineProperty(match, "advance", {
Object.defineProperty(match, 'advance', {
value: function (count) {
this.splice(0, count);
}
},
});
var seq,
rep = "";
rep = '';
while ((seq = match[0])) {

@@ -170,7 +170,7 @@ match.advance(1);

other &&
(other = typeof other === "function" ? other(match) : other)
(other = typeof other === 'function' ? other(match) : other)
) {
// If reset signal is encountered, we have to reset everything.
var ret = "";
if (seq === "0") {
var ret = '';
if (seq === '0') {
ret += _closeTags[seq](ansiCodes);

@@ -182,3 +182,3 @@ }

ansiCodes.pop();
return "</span>";
return '</span>';
}

@@ -188,3 +188,3 @@ // Open tag.

return (
ret + (other[0] === "<" ? other : '<span style="' + other + ';">')
ret + (other[0] === '<' ? other : '<span style="' + other + ';">')
);

@@ -194,3 +194,3 @@ }

var ct = _closeTags[seq];
if (typeof ct === "function") {
if (typeof ct === 'function') {
return ct(ansiCodes);

@@ -202,5 +202,5 @@ } else if (ct) {

}
return "";
return '';
}
}
},
);

@@ -210,3 +210,3 @@

var l = ansiCodes.length;
l > 0 && (ret += Array(l + 1).join("</span>"));
l > 0 && (ret += Array(l + 1).join('</span>'));

@@ -221,4 +221,4 @@ return ret;

ansiHTML.setColors = function (colors) {
if (typeof colors !== "object") {
throw new Error("`colors` parameter must be an Object.");
if (typeof colors !== 'object') {
throw new Error('`colors` parameter must be an Object.');
}

@@ -233,4 +233,4 @@

}
if ("reset" === key) {
if (typeof hex === "string") {
if ('reset' === key) {
if (typeof hex === 'string') {
hex = [hex];

@@ -242,9 +242,9 @@ }

hex.some(function (h) {
return typeof h !== "string";
return typeof h !== 'string';
})
) {
throw new Error(
"The value of `" +
key +
"` property must be an Array and each item could only be a hex string, e.g.: FF0000"
'The value of `' +
key +
'` property must be an Array and each item could only be a hex string, e.g.: FF0000',
);

@@ -262,5 +262,7 @@ }

hex = hex.slice(0, 2);
} else if (typeof hex !== "string") {
} else if (typeof hex !== 'string') {
throw new Error(
"The value of `" + key + "` property must be a hex string, e.g.: FF0000"
'The value of `' +
key +
'` property must be a hex string, e.g.: FF0000',
);

@@ -287,11 +289,11 @@ }

if (Object.defineProperty) {
Object.defineProperty(ansiHTML.tags, "open", {
Object.defineProperty(ansiHTML.tags, 'open', {
get: function () {
return _openTags;
}
},
});
Object.defineProperty(ansiHTML.tags, "close", {
Object.defineProperty(ansiHTML.tags, 'close', {
get: function () {
return _closeTags;
}
},
});

@@ -305,19 +307,19 @@ } else {

// reset all
_openTags["0"] =
"font-weight:normal;opacity:1;color:#" +
_openTags['0'] =
'font-weight:normal;opacity:1;color:#' +
colors.reset[0] +
";background:#" +
';background:#' +
colors.reset[1];
// inverse
_openTags["7"] =
"color:#" + colors.reset[1] + ";background:#" + colors.reset[0];
_openTags['7'] =
'color:#' + colors.reset[1] + ';background:#' + colors.reset[0];
// dark grey
_openTags["90"] = "color:#" + colors.darkgrey;
_openTags['90'] = 'color:#' + colors.darkgrey;
for (var code in _styles) {
var color = _styles[code];
var oriColor = colors[color] || "000";
_openTags[code] = "color:#" + oriColor;
var oriColor = colors[color] || '000';
_openTags[code] = 'color:#' + oriColor;
code = parseInt(code);
_openTags[(code + 10).toString()] = "background:#" + oriColor;
_openTags[(code + 10).toString()] = 'background:#' + oriColor;
}

@@ -324,0 +326,0 @@ }

@@ -96,3 +96,3 @@ /**

'unhandledrejection',
createRejectionHandler
createRejectionHandler,
);

@@ -103,2 +103,2 @@

handleUnhandledRejection: handleUnhandledRejection,
};
};

@@ -42,3 +42,5 @@ /**

lines = lines.filter(function (line, index, arr) {
return index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim();
return (
index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()
);
});

@@ -67,4 +69,10 @@

// because they're normally from user code generated by webpack.
message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y
message = message.replace(/^\s*at\s((?!webpack:).)*<anonymous>[\s)]*(\n|$)/gm, ''); // at ... <anonymous>
message = message.replace(
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
'',
); // at ... ...:x:y
message = message.replace(
/^\s*at\s((?!webpack:).)*<anonymous>[\s)]*(\n|$)/gm,
'',
); // at ... <anonymous>
message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous>

@@ -85,3 +93,5 @@

if (typeof errorObjOrMessage === 'object') {
return formatMessage([errorObjOrMessage.moduleName, errorObjOrMessage.message].join('\n'));
return formatMessage(
[errorObjOrMessage.moduleName, errorObjOrMessage.message].join('\n'),
);
}

@@ -99,2 +109,2 @@ // Webpack 4 compilation errors are strings

module.exports = formatWebpackErrors;
module.exports = formatWebpackErrors;

@@ -15,3 +15,3 @@ function runWithRetry(callback, maxRetries) {

},
Math.pow(10, currentCount)
Math.pow(10, currentCount),
);

@@ -24,2 +24,2 @@ }

module.exports = runWithRetry;
module.exports = runWithRetry;

@@ -1,3 +0,3 @@

import type { Compiler } from "@rspack/core";
import type { NormalizedPluginOptions, PluginOptions } from "./options";
import type { Compiler } from '@rspack/core';
import type { NormalizedPluginOptions, PluginOptions } from './options';
export type { PluginOptions };

@@ -4,0 +4,0 @@ declare class ReactRefreshRspackPlugin {

@@ -9,7 +9,7 @@ "use strict";

const getSocketIntegration_1 = require("./utils/getSocketIntegration");
const reactRefreshPath = require.resolve("../client/reactRefresh.js");
const reactRefreshEntryPath = require.resolve("../client/reactRefreshEntry.js");
const refreshUtilsPath = require.resolve("../client/refreshUtils.js");
const refreshRuntimeDirPath = node_path_1.default.dirname(require.resolve("react-refresh", {
paths: [reactRefreshPath]
const reactRefreshPath = require.resolve('../client/reactRefresh.js');
const reactRefreshEntryPath = require.resolve('../client/reactRefreshEntry.js');
const refreshUtilsPath = require.resolve('../client/refreshUtils.js');
const refreshRuntimeDirPath = node_path_1.default.dirname(require.resolve('react-refresh', {
paths: [reactRefreshPath],
}));

@@ -20,3 +20,3 @@ const runtimePaths = [

refreshUtilsPath,
refreshRuntimeDirPath
refreshRuntimeDirPath,
];

@@ -31,6 +31,6 @@ class ReactRefreshRspackPlugin {

// Ref: https://github.com/webpack/webpack/issues/7074
(compiler.options.mode !== "development" ||
(compiler.options.mode !== 'development' ||
// We also check for production process.env.NODE_ENV,
// in case it was set and mode is non-development (e.g. 'none')
(process.env.NODE_ENV && process.env.NODE_ENV === "production")) &&
(process.env.NODE_ENV && process.env.NODE_ENV === 'production')) &&
!this.options.forceEnable) {

@@ -41,7 +41,7 @@ return;

devServer: compiler.options.devServer,
options: this.options
options: this.options,
});
for (const entry of addEntries.prependEntries) {
new compiler.webpack.EntryPlugin(compiler.context, entry, {
name: undefined
name: undefined,
}).apply(compiler);

@@ -51,14 +51,16 @@ }

new compiler.webpack.EntryPlugin(compiler.context, entry, {
name: undefined
name: undefined,
}).apply(compiler);
}
new compiler.webpack.ProvidePlugin({
$ReactRefreshRuntime$: reactRefreshPath
$ReactRefreshRuntime$: reactRefreshPath,
}).apply(compiler);
compiler.options.module.rules.unshift({
// biome-ignore lint: exists
include: this.options.include,
exclude: {
or: [this.options.exclude, [...runtimePaths]].filter(Boolean)
// biome-ignore lint: exists
or: [this.options.exclude, [...runtimePaths]].filter(Boolean),
},
use: "builtin:react-refresh-loader"
use: 'builtin:react-refresh-loader',
});

@@ -69,6 +71,6 @@ const definedModules = {

compiler.options.output.uniqueName ||
compiler.options.output.library))
compiler.options.output.library)),
};
const providedModules = {
__react_refresh_utils__: refreshUtilsPath
__react_refresh_utils__: refreshUtilsPath,
};

@@ -90,6 +92,6 @@ if (this.options.overlay === false) {

new compiler.webpack.ProvidePlugin(providedModules).apply(compiler);
const refreshPath = node_path_1.default.dirname(require.resolve("react-refresh"));
const refreshPath = node_path_1.default.dirname(require.resolve('react-refresh'));
compiler.options.resolve.alias = {
"react-refresh": refreshPath,
...compiler.options.resolve.alias
'react-refresh': refreshPath,
...compiler.options.resolve.alias,
};

@@ -96,0 +98,0 @@ }

@@ -1,2 +0,2 @@

import type { IntegrationType } from "./utils/getSocketIntegration";
import type { IntegrationType } from './utils/getSocketIntegration';
interface OverlayOptions {

@@ -3,0 +3,0 @@ entry: string;

@@ -6,4 +6,4 @@ "use strict";

// TODO: should we also add default for null?
if (typeof object[property] === "undefined" &&
typeof defaultValue !== "undefined") {
if (typeof object[property] === 'undefined' &&
typeof defaultValue !== 'undefined') {
object[property] = defaultValue;

@@ -15,5 +15,5 @@ }

const defaultOverlay = {
entry: require.resolve("../client/errorOverlayEntry.js"),
module: require.resolve("../client/overlay/index.js"),
sockIntegration: "wds"
entry: require.resolve('../client/errorOverlayEntry.js'),
module: require.resolve('../client/overlay/index.js'),
sockIntegration: 'wds',
};

@@ -23,3 +23,3 @@ if (!options) {

}
if (typeof options === "undefined" || options === true) {
if (typeof options === 'undefined' || options === true) {
return defaultOverlay;

@@ -34,6 +34,6 @@ }

function normalizeOptions(options) {
d(options, "exclude", /node_modules/i);
d(options, "include", /\.([cm]js|[jt]sx?|flow)$/i);
d(options, "library");
d(options, "forceEnable", false);
d(options, 'exclude', /node_modules/i);
d(options, 'include', /\.([cm]js|[jt]sx?|flow)$/i);
d(options, 'library');
d(options, 'forceEnable', false);
options.overlay = normalizeOverlay(options.overlay);

@@ -40,0 +40,0 @@ return options;

@@ -6,3 +6,3 @@ "use strict";

// but is not supported in all browsers (most notably, IE).
if ("currentScript" in document) {
if ('currentScript' in document) {
// In some cases, `document.currentScript` would be `null` even if the browser supports it:

@@ -13,12 +13,12 @@ // e.g. asynchronous chunks on Firefox.

return;
return document.currentScript.getAttribute("src");
return document.currentScript.getAttribute('src');
}
// Fallback to getting all scripts running in the document,
// and finding the last one injected.
const scriptElementsWithSrc = Array.prototype.filter.call(document.scripts || [], elem => elem.getAttribute("src"));
const scriptElementsWithSrc = Array.prototype.filter.call(document.scripts || [], (elem) => elem.getAttribute('src'));
if (!scriptElementsWithSrc.length)
return;
const currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
return currentScript.getAttribute("src");
return currentScript.getAttribute('src');
}
exports.default = getCurrentScriptSource;

@@ -1,2 +0,2 @@

import type { WDSMetaObj } from "./getWDSMetadata";
import type { WDSMetaObj } from './getWDSMetadata';
export interface SocketUrlParts {

@@ -3,0 +3,0 @@ auth?: string;

@@ -32,2 +32,3 @@ "use strict";

// and will have no effect if `scriptSource` is a fully valid URL.
// biome-ignore lint: reason
url = new URL(scriptSource, window.location.href);

@@ -50,3 +51,3 @@ }

// `file://` URLs has `'null'` origin
if (url.origin !== "null") {
if (url.origin !== 'null') {
urlParts.hostname = url.hostname;

@@ -60,7 +61,7 @@ }

// This is hard-coded in WDS v4
urlParts.pathname = "/ws";
urlParts.pathname = '/ws';
}
else {
// This is hard-coded in WDS v3
urlParts.pathname = "/sockjs-node";
urlParts.pathname = '/sockjs-node';
}

@@ -71,4 +72,4 @@ }

// such as 'about:blank' or 'file://' URLs.
const isEmptyHostname = urlParts.hostname === "0.0.0.0" ||
urlParts.hostname === "[::]" ||
const isEmptyHostname = urlParts.hostname === '0.0.0.0' ||
urlParts.hostname === '[::]' ||
!urlParts.hostname;

@@ -79,3 +80,3 @@ // We only re-assign the hostname if it is empty,

window.location.hostname &&
window.location.protocol.indexOf("http") === 0) {
window.location.protocol.indexOf('http') === 0) {
urlParts.hostname = window.location.hostname;

@@ -89,3 +90,3 @@ }

(urlParts.hostname &&
(isEmptyHostname || window.location.protocol === "https:"))) {
(isEmptyHostname || window.location.protocol === 'https:'))) {
urlParts.protocol = window.location.protocol;

@@ -99,7 +100,7 @@ }

throw new Error([
"[React Refresh] Failed to get an URL for the socket connection.",
'[React Refresh] Failed to get an URL for the socket connection.',
"This usually means that the current executed script doesn't have a `src` attribute set.",
"You should either specify the socket path parameters under the `devServer` key in your Rspack config, or use the `overlay` option.",
"https://www.rspack.dev/guide/tech/react#fast-refresh"
].join("\n"));
'You should either specify the socket path parameters under the `devServer` key in your Rspack config, or use the `overlay` option.',
'https://www.rspack.dev/guide/tech/react#fast-refresh',
].join('\n'));
}

@@ -111,5 +112,5 @@ return {

protocol: urlParts.protocol,
port: urlParts.port || undefined
port: urlParts.port || undefined,
};
}
exports.default = getSocketUrlParts;

@@ -1,3 +0,3 @@

import type { SocketUrlParts } from "./getSocketUrlParts";
import type { WDSMetaObj } from "./getWDSMetadata";
import type { SocketUrlParts } from './getSocketUrlParts';
import type { WDSMetaObj } from './getWDSMetadata';
/**

@@ -4,0 +4,0 @@ * Create a valid URL from parsed URL parts.

@@ -10,3 +10,3 @@ "use strict";

function urlFromParts(urlParts, metadata = {}) {
let fullProtocol = "http:";
let fullProtocol = 'http:';
if (urlParts.protocol) {

@@ -16,3 +16,3 @@ fullProtocol = urlParts.protocol;

if (metadata.enforceWs) {
fullProtocol = fullProtocol.replace(/^(?:http|.+-extension|file)/i, "ws");
fullProtocol = fullProtocol.replace(/^(?:http|.+-extension|file)/i, 'ws');
}

@@ -22,3 +22,3 @@ fullProtocol = `${fullProtocol}//`;

if (urlParts.auth) {
const fullAuth = `${urlParts.auth.split(":").map(encodeURIComponent).join(":")}@`;
const fullAuth = `${urlParts.auth.split(':').map(encodeURIComponent).join(':')}@`;
fullHost = fullAuth + fullHost;

@@ -25,0 +25,0 @@ }

@@ -8,5 +8,5 @@ export interface WDSMetaObj {

constructor(url: string);
onOpen(f: (...args: any[]) => void): void;
onClose(f: (...args: any[]) => void): void;
onMessage(f: (...args: any[]) => void): void;
onOpen(f: (...args: unknown[]) => void): void;
onClose(f: (...args: unknown[]) => void): void;
onMessage(f: (...args: unknown[]) => void): void;
}

@@ -13,0 +13,0 @@ export interface SocketClient {

@@ -5,5 +5,5 @@ "use strict";

let enforceWs = false;
if (typeof SocketClient.name !== "undefined" &&
if (typeof SocketClient.name !== 'undefined' &&
SocketClient.name !== null &&
SocketClient.name.toLowerCase().includes("websocket")) {
SocketClient.name.toLowerCase().includes('websocket')) {
enforceWs = true;

@@ -13,3 +13,3 @@ }

// WDS versions <=3.5.0
if (!("onMessage" in SocketClient.prototype)) {
if (!('onMessage' in SocketClient.prototype)) {
version = 3;

@@ -19,4 +19,4 @@ }

// WDS versions >=3.5.0 <4
if ("getClientPath" in SocketClient ||
Object.getPrototypeOf(SocketClient).name === "BaseClient") {
if ('getClientPath' in SocketClient ||
Object.getPrototypeOf(SocketClient).name === 'BaseClient') {
version = 3;

@@ -30,5 +30,5 @@ }

enforceWs: enforceWs,
version: version
version: version,
};
}
exports.default = getWDSMetadata;

@@ -1,2 +0,2 @@

import type { SocketClient } from "./utils/getWDSMetadata";
import type { SocketClient } from './utils/getWDSMetadata';
declare global {

@@ -13,2 +13,2 @@ var __webpack_dev_server_client__: SocketClient | {

*/
export declare function init(messageHandler: (...args: any[]) => void, resourceQuery: string): void;
export declare function init(messageHandler: (...args: unknown[]) => void, resourceQuery: string): void;

@@ -26,5 +26,5 @@ "use strict";

function init(messageHandler, resourceQuery) {
if (typeof __webpack_dev_server_client__ !== "undefined") {
if (typeof __webpack_dev_server_client__ !== 'undefined') {
let SocketClient;
if ("default" in __webpack_dev_server_client__) {
if ('default' in __webpack_dev_server_client__) {
SocketClient = __webpack_dev_server_client__.default;

@@ -31,0 +31,0 @@ }

@@ -1,2 +0,2 @@

import type { NormalizedPluginOptions } from "../options";
import type { NormalizedPluginOptions } from '../options';
export interface AdditionalEntries {

@@ -6,5 +6,5 @@ prependEntries: string[];

}
export declare function getAdditionalEntries({ devServer, options }: {
export declare function getAdditionalEntries({ devServer, options, }: {
devServer: any;
options: NormalizedPluginOptions;
}): AdditionalEntries;

@@ -8,3 +8,3 @@ "use strict";

const node_querystring_1 = __importDefault(require("node:querystring"));
function getAdditionalEntries({ devServer, options }) {
function getAdditionalEntries({ devServer, options, }) {
const resourceQuery = {};

@@ -14,3 +14,3 @@ if (devServer) {

let { host, path, port } = devServer;
let protocol = https || http2 ? "https" : "http";
let protocol = https || http2 ? 'https' : 'http';
if (sockHost)

@@ -24,3 +24,3 @@ host = sockHost;

let parsedUrl = client.webSocketURL;
if (typeof parsedUrl === "string")
if (typeof parsedUrl === 'string')
parsedUrl = new URL(parsedUrl);

@@ -37,3 +37,3 @@ let auth;

.filter(Boolean)
.join("@");
.join('@');
}

@@ -44,3 +44,3 @@ if (parsedUrl.pathname != null) {

if (parsedUrl.port != null) {
port = !["0", "auto"].includes(String(parsedUrl.port))
port = !['0', 'auto'].includes(String(parsedUrl.port))
? parsedUrl.port

@@ -51,5 +51,5 @@ : undefined;

protocol =
parsedUrl.protocol !== "auto"
? parsedUrl.protocol.replace(":", "")
: "ws";
parsedUrl.protocol !== 'auto'
? parsedUrl.protocol.replace(':', '')
: 'ws';
}

@@ -80,7 +80,7 @@ }

return str;
}
},
});
const prependEntries = [
// React-refresh runtime
require.resolve("../../client/reactRefreshEntry")
require.resolve('../../client/reactRefreshEntry'),
];

@@ -91,3 +91,3 @@ const overlayEntries = [

options.overlay?.entry &&
`${require.resolve(options.overlay.entry)}${queryString ? `?${queryString}` : ""}`
`${require.resolve(options.overlay.entry)}${queryString ? `?${queryString}` : ''}`,
].filter(Boolean);

@@ -94,0 +94,0 @@ return { prependEntries, overlayEntries };

@@ -1,2 +0,2 @@

export type IntegrationType = "wds";
export type IntegrationType = 'wds';
export declare function getSocketIntegration(integrationType: IntegrationType): string;

@@ -7,4 +7,4 @@ "use strict";

switch (integrationType) {
case "wds": {
resolvedSocketIntegration = require.resolve("../sockets/WDSSocket");
case 'wds': {
resolvedSocketIntegration = require.resolve('../sockets/WDSSocket');
break;

@@ -11,0 +11,0 @@ }

{
"name": "@rspack/plugin-react-refresh",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"repository": "https://github.com/rspack-contrib/rspack-plugin-react-refresh",
"license": "MIT",

@@ -20,18 +21,29 @@ "description": "React refresh plugin for rspack",

],
"publishConfig": {
"access": "public",
"provenance": true
"simple-git-hooks": {
"pre-commit": "npx nano-staged"
},
"homepage": "https://rspack.dev",
"bugs": "https://github.com/web-infra-dev/rspack/issues",
"repository": {
"type": "git",
"url": "https://github.com/web-infra-dev/rspack",
"directory": "packages/rspack-plugin-react-refresh"
"nano-staged": {
"*.{js,jsx,ts,tsx,mjs,cjs}": [
"biome check --write --no-errors-on-unmatched"
]
},
"devDependencies": {
"@biomejs/biome": "^1.8.3",
"@rspack/core": "1.0.0-beta.3",
"@rspack/test-tools": "1.0.0-beta.3",
"@rspack/dev-server": "1.0.0-beta.3",
"@types/node": "^20.14.13",
"@types/jest": "29.5.12",
"react-refresh": "^0.14.0",
"typescript": "5.0.2",
"@rspack/core": "1.0.0-beta.3",
"@rspack/plugin-react-refresh": "1.0.0-beta.3"
"cross-env": "^7.0.3",
"execa": "9.3.0",
"fs-extra": "11.2.0",
"jest": "29.7.0",
"jest-cli": "29.7.0",
"jest-environment-node": "29.7.0",
"nano-staged": "^0.8.0",
"semver": "7.6.3",
"simple-git-hooks": "^2.11.1",
"ts-jest": "29.1.2",
"typescript": "5.0.2"
},

@@ -50,8 +62,5 @@ "dependencies": {

},
"jest": {
"watchPathIgnorePatterns": [
"<rootDir>/dist",
"<rootDir>/tests/dist"
],
"testEnvironment": "../../scripts/test/patch-node-env.cjs"
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},

@@ -61,6 +70,7 @@ "scripts": {

"dev": "tsc -b -w",
"lint": "biome check .",
"lint:write": "biome check . --write",
"test": "jest --colors",
"api-extractor": "api-extractor run --verbose",
"api-extractor:ci": "api-extractor run --verbose || diff temp/api.md etc/api.md"
"release": "node ./scripts/release.mjs"
}
}

@@ -8,10 +8,74 @@ <picture>

React refresh plugin for rspack.
React refresh plugin for [Rspack](https://github.com/web-infra-dev/rspack).
## Documentation
## Installation
See [https://rspack.dev](https://rspack.dev) for details.
First you need to install this plugin and its dependencies:
```bash
npm add @rspack/plugin-react-refresh react-refresh -D
# or
yarn add @rspack/plugin-react-refresh react-refresh -D
# or
pnpm add @rspack/plugin-react-refresh react-refresh -D
# or
bun add @rspack/plugin-react-refresh react-refresh -D
```
## Usage
Enabling [React Fast Refresh](https://reactnative.dev/docs/fast-refresh) functionality primarily involves two aspects: code injection and code transformation.
- Code injection will inject some code from the [react-refresh](https://www.npmjs.com/package/react-refresh) package, as well as some custom runtime code, all of which are integrated in this plugin and can be injected through.
- Code transformation can be added through loaders, such as [jsc.transform.react.refresh](https://swc.rs/docs/configuration/compilation#jsctransformreactrefresh) for [swc-loader](https://swc.rs/docs/usage/swc-loader) or the [react-refresh/babel](https://github.com/facebook/react/tree/main/packages/react-refresh) for [babel-loader](https://github.com/babel/babel-loader).
```js
const ReactRefreshPlugin = require('@rspack/plugin-react-refresh');
const isDev = process.env.NODE_ENV === 'development';
module.exports = {
experiments: {
rspackFuture: {
disableTransformByDefault: true,
},
},
// ...
mode: isDev ? 'development' : 'production',
module: {
rules: [
{
test: /\.jsx$/,
use: {
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'ecmascript',
jsx: true,
},
transform: {
react: {
development: isDev,
refresh: isDev,
},
},
},
},
},
},
],
},
plugins: [isDev && new ReactRefreshPlugin()].filter(Boolean),
};
```
Compared to the previous approach, this method decouples the React Fast Refresh code injection logic from the transformation logic. The code injection logic is handled uniformly by this plugin, while the code transformation is handled by loaders. This means that this plugin can be used in conjunction with `builtin:swc-loader`, `swc-loader`, or `babel-loader`.
## Example
- For usage with `builtin:swc-loader`, you can refer to the example at [examples/react-refresh](https://github.com/rspack-contrib/rspack-examples/tree/main/rspack/react-refresh/rspack.config.js), When using with `swc-loader`, simply replace `builtin:swc-loader` with `swc-loader`.
- For usage with `babel-loader`, you can refer to the example at [examples/react-refresh-babel-loader](https://github.com/rspack-contrib/rspack-examples/tree/main/rspack/react-refresh-babel-loader/rspack.config.js)
## License
Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE).

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc