Skip to content

🎥 Make videos programmatically with React

remove webpack-hot-middleware

Jonny Burger2e2767bde184
diff --git a/packages/bundler/package.json b/packages/bundler/package.json
index 50791bb9a2..d5dc34f221 100644
--- a/packages/bundler/package.json
+++ b/packages/bundler/package.json
@@ -33,8 +33,7 @@
"source-map": "^0.5.7",
"source-map-loader": "^3.0.0",
"style-loader": "^2.0.0",
- "webpack": "5.60.0",
- "webpack-hot-middleware": "^2.25.0"
+ "webpack": "5.60.0"
},
"peerDependencies": {
"react": "^17.0.1",
diff --git a/packages/bundler/src/fast-refresh/helpers.ts b/packages/bundler/src/fast-refresh/helpers.ts
index c2cbfb209c..1ef111e52c 100644
--- a/packages/bundler/src/fast-refresh/helpers.ts
+++ b/packages/bundler/src/fast-refresh/helpers.ts
@@ -143,36 +143,28 @@ function getRefreshBoundarySignature(moduleExports: unknown) {
return signature;
}
-let isUpdateScheduled = false;
function scheduleUpdate() {
- if (isUpdateScheduled) {
- return;
- }
+ const execute = () => {
+ try {
+ RefreshRuntime.performReactRefresh();
+ } catch (err) {
+ console.warn(
+ 'Warning: Failed to re-render. We will retry on the next Fast Refresh event.\n' +
+ err
+ );
+ }
+ };
- function canApplyUpdate() {
- return module.hot?.status() === 'idle';
+ // Only trigger refresh if the webpack HMR state is idle
+ if (module.hot?.status() === 'idle') {
+ return;
}
- isUpdateScheduled = true;
- setTimeout(() => {
- isUpdateScheduled = false;
-
- // Only trigger refresh if the webpack HMR state is idle
- if (canApplyUpdate()) {
- try {
- RefreshRuntime.performReactRefresh();
- } catch (err) {
- console.warn(
- 'Warning: Failed to re-render. We will retry on the next Fast Refresh event.\n' +
- err
- );
- }
-
- return;
+ module.hot?.addStatusHandler((status) => {
+ if (status === 'idle') {
+ execute();
}
-
- return scheduleUpdate();
- }, 30);
+ });
}
export default {
diff --git a/packages/bundler/src/hot-middleware/client.ts b/packages/bundler/src/hot-middleware/client.ts
index 50b696cb0d..61a192fd25 100644
--- a/packages/bundler/src/hot-middleware/client.ts
+++ b/packages/bundler/src/hot-middleware/client.ts
@@ -1,18 +1,6 @@
import {processUpdate} from './process-update';
-
-const options = {
- path: '/__webpack_hmr',
- timeout: 20 * 1000,
- overlay: true,
- reload: false,
- log: true,
- warn: true,
- name: '',
- autoConnect: true,
- overlayStyles: {},
- overlayWarnings: false,
- ansiColors: {},
-};
+import {stripAnsi} from './strip-ansi';
+import {HotMiddlewareMessage, hotMiddlewareOptions} from './types';
if (typeof window === 'undefined') {
// do nothing
@@ -20,7 +8,7 @@ if (typeof window === 'undefined') {
console.warn(
'Unsupported browser: You need a browser that supports EventSource '
);
-} else if (options.autoConnect) {
+} else if (hotMiddlewareOptions.autoConnect) {
connect();
}
@@ -28,31 +16,31 @@ function setOptionsAndConnect() {
connect();
}
-function EventSourceWrapper() {
+function eventSourceWrapper() {
let source: EventSource;
let lastActivity = Date.now();
- const listeners = [];
+ const listeners: ((ev: MessageEvent) => void)[] = [];
init();
const timer = setInterval(() => {
- if (Date.now() - lastActivity > options.timeout) {
+ if (Date.now() - lastActivity > hotMiddlewareOptions.timeout) {
handleDisconnect();
}
- }, options.timeout / 2);
+ }, hotMiddlewareOptions.timeout / 2);
function init() {
- source = new window.EventSource(options.path);
+ source = new window.EventSource(hotMiddlewareOptions.path);
source.onopen = handleOnline;
source.onerror = handleDisconnect;
source.onmessage = handleMessage;
}
function handleOnline() {
- if (options.log) console.log('[HMR] connected');
+ console.log('[Fast Refresh] connected');
lastActivity = Date.now();
}
- function handleMessage(event) {
+ function handleMessage(event: MessageEvent) {
lastActivity = Date.now();
for (let i = 0; i < listeners.length; i++) {
listeners[i](event);
@@ -62,34 +50,44 @@ function EventSourceWrapper() {
function handleDisconnect() {
clearInterval(timer);
source.close();
- setTimeout(init, options.timeout);
+ setTimeout(init, hotMiddlewareOptions.timeout);
}
return {
- addMessageListener(fn) {
+ addMessageListener(fn: (msg: MessageEvent) => void) {
listeners.push(fn);
},
};
}
+declare global {
+ interface Window {
+ __whmEventSourceWrapper: {
+ [key: string]: ReturnType<typeof eventSourceWrapper>;
+ };
+ __webpack_hot_middleware_reporter__: Reporter;
+ }
+}
+
function getEventSourceWrapper() {
if (!window.__whmEventSourceWrapper) {
window.__whmEventSourceWrapper = {};
}
- if (!window.__whmEventSourceWrapper[options.path]) {
+ if (!window.__whmEventSourceWrapper[hotMiddlewareOptions.path]) {
// cache the wrapper for other entries loaded on
- // the same page with the same options.path
- window.__whmEventSourceWrapper[options.path] = EventSourceWrapper();
+ // the same page with the same hotMiddlewareOptions.path
+ window.__whmEventSourceWrapper[hotMiddlewareOptions.path] =
+ eventSourceWrapper();
}
- return window.__whmEventSourceWrapper[options.path];
+ return window.__whmEventSourceWrapper[hotMiddlewareOptions.path];
}
function connect() {
getEventSourceWrapper().addMessageListener(handleMessage);
- function handleMessage(event) {
+ function handleMessage(event: MessageEvent) {
if (event.data === '\uD83D\uDC93') {
return;
}
@@ -97,7 +95,7 @@ function connect() {
try {
processMessage(JSON.parse(event.data));
} catch (ex) {
- if (options.warn) {
+ if (hotMiddlewareOptions.warn) {
console.warn('Invalid HMR message: ' + event.data + '\n' + ex);
}
}
@@ -108,8 +106,8 @@ function connect() {
// in case the client is being used by multiple bundles
// we only want to report once.
// all the errors will go to all clients
-const singletonKey = '__webpack_hot_middleware_reporter__';
-let reporter;
+const singletonKey = '__webpack_hot_middleware_reporter__' as const;
+let reporter: Reporter;
if (typeof window !== 'undefined') {
if (!window[singletonKey]) {
window[singletonKey] = createReporter();
@@ -118,30 +116,27 @@ if (typeof window !== 'undefined') {
reporter = window[singletonKey];
}
-function createReporter() {
- const strip = require('strip-ansi');
-
- let overlay;
- if (typeof document !== 'undefined' && options.overlay) {
- overlay = require('./client-overlay')({
- ansiColors: options.ansiColors,
- overlayStyles: options.overlayStyles,
- });
- }
+type Reporter = ReturnType<typeof createReporter>;
+function createReporter() {
const styles = {
errors: 'color: #ff0000;',
warnings: 'color: #999933;',
};
- let previousProblems = null;
+ let previousProblems: string | null = null;
+
+ function log(type: 'errors' | 'warnings', obj: HotMiddlewareMessage) {
+ if (obj.action === 'building') {
+ console.log('[Fast Refresh] Building');
+ return;
+ }
- function log(type, obj) {
const newProblems = obj[type]
.map((msg) => {
- return strip(msg);
+ return stripAnsi(msg as string);
})
.join('\n');
- if (previousProblems == newProblems) {
+ if (previousProblems === newProblems) {
return;
}
@@ -150,7 +145,7 @@ function createReporter() {
const style = styles[type];
const name = obj.name ? "'" + obj.name + "' " : '';
const title =
- '[HMR] bundle ' + name + 'has ' + obj[type].length + ' ' + type;
+ '[Fast Refresh] bundle ' + name + 'has ' + obj[type].length + ' ' + type;
// NOTE: console.warn or console.error will print the stack trace
// which isn't helpful here, so using console.log to escape it.
if (console.group && console.groupEnd) {
@@ -170,64 +165,50 @@ function createReporter() {
cleanProblemsCache() {
previousProblems = null;
},
- problems(type, obj) {
- if (options.warn) {
+ problems(type: 'errors' | 'warnings', obj: HotMiddlewareMessage) {
+ if (hotMiddlewareOptions.warn) {
log(type, obj);
}
- if (overlay) {
- if (options.overlayWarnings || type === 'errors') {
- overlay.showProblems(type, obj[type]);
- return false;
- }
-
- overlay.clear();
- }
-
return true;
},
- success() {
- if (overlay) overlay.clear();
- },
- useCustomOverlay(customOverlay) {
- overlay = customOverlay;
- },
+ success: () => undefined,
};
}
-let customHandler;
-let subscribeAllHandler;
+let customHandler: ((msg: HotMiddlewareMessage) => void) | undefined;
+let subscribeAllHandler: ((msg: HotMiddlewareMessage) => void) | undefined;
-function processMessage(obj) {
+function processMessage(obj: HotMiddlewareMessage) {
switch (obj.action) {
case 'building':
- if (options.log) {
- console.log(
- '[HMR] bundle ' +
- (obj.name ? "'" + obj.name + "' " : '') +
- 'rebuilding'
- );
- }
+ console.log(
+ '[Fast refresh] bundle ' +
+ (obj.name ? "'" + obj.name + "' " : '') +
+ 'rebuilding'
+ );
break;
case 'built':
- if (options.log) {
- console.log(
- '[HMR] bundle ' +
- (obj.name ? "'" + obj.name + "' " : '') +
- 'rebuilt in ' +
- obj.time +
- 'ms'
- );
- }
+ console.log(
+ '[Fast refresh] bundle ' +
+ (obj.name ? "'" + obj.name + "' " : '') +
+ 'rebuilt in ' +
+ obj.time +
+ 'ms'
+ );
// fall through
- case 'sync':
- if (obj.name && options.name && obj.name !== options.name) {
+ case 'sync': {
+ if (
+ obj.name &&
+ hotMiddlewareOptions.name &&
+ obj.name !== hotMiddlewareOptions.name
+ ) {
return;
}
- var applyUpdate = true;
+ let applyUpdate = true;
if (obj.errors.length > 0) {
if (reporter) reporter.problems('errors', obj);
applyUpdate = false;
@@ -242,10 +223,12 @@ function processMessage(obj) {
}
if (applyUpdate) {
- processUpdate(obj.hash, obj.modules, options);
+ processUpdate(obj.hash, obj.modules, hotMiddlewareOptions);
}
break;
+ }
+
default:
if (customHandler) {
customHandler(obj);
@@ -258,10 +241,10 @@ function processMessage(obj) {
}
module.exports = {
- subscribeAll(handler) {
+ subscribeAll(handler: (msg: HotMiddlewareMessage) => void) {
subscribeAllHandler = handler;
},
- subscribe(handler) {
+ subscribe(handler: (msg: HotMiddlewareMessage) => void) {
customHandler = handler;
},
setOptionsAndConnect,
diff --git a/packages/bundler/src/hot-middleware/index.tsx b/packages/bundler/src/hot-middleware/index.tsx
index 1590510b7c..3f7ba8e3ff 100644
--- a/packages/bundler/src/hot-middleware/index.tsx
+++ b/packages/bundler/src/hot-middleware/index.tsx
@@ -1,8 +1,15 @@
+import {Request, Response} from 'express';
import webpack from 'webpack';
-
-const {parse} = require('url');
-
-exports.pathMatch = function (url, path) {
+import {
+ HotMiddlewareMessage,
+ hotMiddlewareOptions,
+ HotMiddlewareOptions,
+ ModuleMap,
+ WebpackStats,
+} from './types';
+import {parse} from 'url';
+
+const pathMatch = function (url: string, path: string) {
try {
return parse(url).pathname === path;
} catch (e) {
@@ -10,15 +17,11 @@ exports.pathMatch = function (url, path) {
}
};
-export function webpackHotMiddleware(compiler: webpack.Compiler, opts) {
- opts = opts || {};
- opts.log =
- typeof opts.log === 'undefined' ? console.log.bind(console) : opts.log;
- opts.path = opts.path || '/__webpack_hmr';
- opts.heartbeat = opts.heartbeat || 10 * 1000;
-
- let eventStream = createEventStream(opts.heartbeat);
- let latestStats = null;
+export function webpackHotMiddleware(compiler: webpack.Compiler) {
+ let eventStream: EventStream | null = createEventStream(
+ hotMiddlewareOptions.heartbeat
+ );
+ let latestStats: webpack.Stats | null = null;
let closed = false;
compiler.hooks.invalid.tap('webpack-hot-middleware', onInvalid);
@@ -27,33 +30,34 @@ export function webpackHotMiddleware(compiler: webpack.Compiler, opts) {
function onInvalid() {
if (closed) return;
latestStats = null;
- if (opts.log) opts.log('webpack building...');
- eventStream.publish({
+ hotMiddlewareOptions.log('webpack building...');
+ eventStream?.publish({
action: 'building',
});
}
- function onDone(statsResult) {
+ function onDone(statsResult: webpack.Stats) {
if (closed) return;
// Keep hold of latest stats so they can be propagated to new clients
latestStats = statsResult;
- publishStats('built', latestStats, eventStream, opts.log);
+ publishStats('built', latestStats, eventStream, hotMiddlewareOptions.log);
}
- const middleware = function (req, res, next) {
+ const middleware = function (req: Request, res: Response, next: () => void) {
if (closed) return next();
- if (!pathMatch(req.url, opts.path)) return next();
- eventStream.handler(req, res);
+
+ if (!pathMatch(req.url, hotMiddlewareOptions.path)) return next();
+ eventStream?.handler(req, res);
if (latestStats) {
// Explicitly not passing in `log` fn as we don't want to log again on
// the server
- publishStats('sync', latestStats, eventStream);
+ publishStats('sync', latestStats, eventStream, hotMiddlewareOptions.log);
}
};
- middleware.publish = function (payload) {
+ middleware.publish = function (payload: HotMiddlewareMessage) {
if (closed) return;
- eventStream.publish(payload);
+ eventStream?.publish(payload);
};
middleware.close = function () {
@@ -61,37 +65,39 @@ export function webpackHotMiddleware(compiler: webpack.Compiler, opts) {
// Can't remove compiler plugins, so we just set a flag and noop if closed
// https://github.com/webpack/tapable/issues/32#issuecomment-350644466
closed = true;
- eventStream.close();
+ eventStream?.close();
eventStream = null;
};
return middleware;
}
-function createEventStream(heartbeat) {
+type EventStream = ReturnType<typeof createEventStream>;
+
+function createEventStream(heartbeat: number) {
let clientId = 0;
- let clients = {};
+ let clients: {[key: string]: Response} = {};
- function everyClient(fn) {
+ function everyClient(fn: (client: Response) => void) {
Object.keys(clients).forEach((id) => {
fn(clients[id]);
});
}
- const interval = setInterval(function heartbeatTick() {
- everyClient((client) => {
+ const interval = setInterval(() => {
+ everyClient((client: Response) => {
client.write('data: \uD83D\uDC93\n\n');
});
}, heartbeat).unref();
return {
close() {
clearInterval(interval);
- everyClient((client) => {
+ everyClient((client: Response) => {
if (!client.finished) client.end();
});
clients = {};
},
- handler(req, res) {
+ handler(req: Request, res: Response) {
const headers = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/event-stream;charset=utf-8',
@@ -101,7 +107,7 @@ function createEventStream(heartbeat) {
'X-Accel-Buffering': 'no',
};
- const isHttp1 = !(parseInt(req.httpVersion) >= 2);
+ const isHttp1 = !(parseInt(req.httpVersion, 10) >= 2);
if (isHttp1) {
req.socket.setKeepAlive(true);
Object.assign(headers, {
@@ -118,7 +124,7 @@ function createEventStream(heartbeat) {
delete clients[id];
});
},
- publish(payload) {
+ publish(payload: HotMiddlewareMessage) {
everyClient((client) => {
client.write('data: ' + JSON.stringify(payload) + '\n\n');
});
@@ -126,7 +132,12 @@ function createEventStream(heartbeat) {
};
}
-function publishStats(action, statsResult, eventStream, log) {
+function publishStats(
+ action: HotMiddlewareMessage['action'],
+ statsResult: webpack.Stats,
+ eventStream: EventStream | null,
+ log: HotMiddlewareOptions['log']
+) {
const stats = statsResult.toJson({
all: false,
cached: true,
@@ -137,8 +148,8 @@ function publishStats(action, statsResult, eventStream, log) {
});
// For multi-compiler, stats will be an object with a 'children' array of stats
const bundles = extractBundles(stats);
- bundles.forEach((stats) => {
- let name = stats.name || '';
+ bundles.forEach((_stats: WebpackStats) => {
+ let name = _stats.name || '';
// Fallback to compilation name in case of 1 bundle (if it exists)
if (bundles.length === 1 && !name && statsResult.compilation) {
@@ -149,40 +160,45 @@ function publishStats(action, statsResult, eventStream, log) {
log(
'webpack built ' +
(name ? name + ' ' : '') +
- stats.hash +
+ _stats.hash +
' in ' +
- stats.time +
+ _stats.time +
'ms'
);
}
- eventStream.publish({
+ eventStream?.publish({
name,
action,
- time: stats.time,
- hash: stats.hash,
- warnings: stats.warnings || [],
- errors: stats.errors || [],
- modules: buildModuleMap(stats.modules),
+ time: _stats.time,
+ hash: _stats.hash,
+ warnings: _stats.warnings || [],
+ errors: _stats.errors || [],
+ modules: buildModuleMap(_stats.modules),
});
});
}
-function extractBundles(stats) {
+function extractBundles(stats: WebpackStats) {
// Stats has modules, single bundle
if (stats.modules) return [stats];
// Stats has children, multiple bundles
- if (stats.children && stats.children.length) return stats.children;
+ if (stats.children?.length) return stats.children;
// Not sure, assume single
return [stats];
}
-function buildModuleMap(modules) {
- const map = {};
+function buildModuleMap(modules: WebpackStats['modules']): ModuleMap {
+ const map: {[key: string]: string} = {};
+ if (!modules) {
+ return map;
+ }
+
modules.forEach((module) => {
- map[module.id] = module.name;
+ const id = module.id as string;
+ map[id] = module.name as string;
});
return map;
}
diff --git a/packages/bundler/src/hot-middleware/process-update.ts b/packages/bundler/src/hot-middleware/process-update.ts
index 171046ffb0..3d33d64961 100644
--- a/packages/bundler/src/hot-middleware/process-update.ts
+++ b/packages/bundler/src/hot-middleware/process-update.ts
@@ -4,28 +4,31 @@
* Original copyright Tobias Koppers @sokra (MIT license)
*/
+import {HotMiddlewareOptions, ModuleMap} from './types';
+
/* global __webpack_hash__ */
if (!module.hot) {
- throw new Error('[HMR] Hot Module Replacement is disabled.');
+ throw new Error('[Fast refresh] Hot Module Replacement is disabled.');
}
const hmrDocsUrl = 'https://webpack.js.org/concepts/hot-module-replacement/'; // eslint-disable-line max-len
-let lastHash;
+let lastHash: string | undefined;
const failureStatuses = {abort: 1, fail: 1};
-const applyOptions = {
+const applyOptions: __WebpackModuleApi.AcceptOptions = {
ignoreUnaccepted: true,
ignoreDeclined: true,
ignoreErrored: true,
onUnaccepted(data) {
console.warn(
- 'Ignored an update to unaccepted module ' + data.chain.join(' -> ')
+ 'Ignored an update to unaccepted module ' +
+ (data.chain ?? []).join(' -> ')
);
},
onDeclined(data) {
console.warn(
- 'Ignored an update to declined module ' + data.chain.join(' -> ')
+ 'Ignored an update to declined module ' + (data.chain ?? []).join(' -> ')
);
},
onErrored(data) {
@@ -40,33 +43,47 @@ const applyOptions = {
},
};
-function upToDate(hash) {
+function upToDate(hash?: string) {
if (hash) lastHash = hash;
- return lastHash == __webpack_hash__;
+ return lastHash === __webpack_hash__;
}
-export const processUpdate = function (hash: string, moduleMap, options) {
+export const processUpdate = function (
+ hash: string | undefined,
+ moduleMap: ModuleMap,
+ options: HotMiddlewareOptions
+) {
const {reload} = options;
- if (!upToDate(hash) && module.hot.status() == 'idle') {
- if (options.log) console.log('[HMR] Checking for updates on the server...');
+ if (!upToDate(hash) && module.hot?.status() === 'idle') {
+ console.log('[Fast refresh] Checking for updates on the server...');
check();
}
- function check() {
- const cb = function (err, updatedModules) {
+ async function check() {
+ const cb = function (
+ err: Error | null,
+ updatedModules: __WebpackModuleApi.ModuleId[]
+ ) {
if (err) return handleError(err);
if (!updatedModules) {
if (options.warn) {
- console.warn('[HMR] Cannot find update (Full reload needed)');
- console.warn('[HMR] (Probably because of restarting the server)');
+ console.warn(
+ '[Fast refresh] Cannot find update (Full reload needed)'
+ );
+ console.warn(
+ '[Fast refresh] (Probably because of restarting the server)'
+ );
}
performReload();
return null;
}
- const applyCallback = function (applyErr, renewedModules) {
+ const applyCallback = function (
+ applyErr: Error | null,
+ renewedModules: __WebpackModuleApi.ModuleId[]
+ ) {
if (applyErr) return handleError(applyErr);
if (!upToDate()) check();
@@ -74,36 +91,41 @@ export const processUpdate = function (hash: string, moduleMap, options) {
logUpdates(updatedModules, renewedModules);
};
- const applyResult = module.hot.apply(applyOptions, applyCallback);
- // webpack 2 promise
- if (applyResult && applyResult.then) {
+ const applyResult = module.hot?.apply(applyOptions, applyCallback);
+ if ((applyResult as unknown as Promise<unknown>)?.then) {
// HotModuleReplacement.runtime.js refers to the result as `outdatedModules`
- applyResult.then((outdatedModules) => {
- applyCallback(null, outdatedModules);
- });
- applyResult.catch(applyCallback);
+ // eslint-disable-next-line promise/no-promise-in-callback
+ (applyResult as unknown as Promise<__WebpackModuleApi.ModuleId[]>)
+ .then((outdatedModules) => {
+ applyCallback(null, outdatedModules);
+ })
+ .catch((_err: Error) => applyCallback(_err, []));
}
};
- const result = module.hot.check(false, cb);
- // webpack 2 promise
- if (result && result.then) {
- result.then((updatedModules) => {
- cb(null, updatedModules);
- });
- result.catch(cb);
+ try {
+ const result = await (module.hot?.check(false, cb) as unknown as Promise<
+ __WebpackModuleApi.ModuleId[]
+ >);
+ cb(null, result);
+ } catch (err) {
+ cb(err as Error, []);
}
}
- function logUpdates(updatedModules, renewedModules) {
- const unacceptedModules = updatedModules.filter((moduleId) => {
- return renewedModules && renewedModules.indexOf(moduleId) < 0;
- });
+ function logUpdates(
+ updatedModules: __WebpackModuleApi.ModuleId[],
+ renewedModules: __WebpackModuleApi.ModuleId[]
+ ) {
+ const unacceptedModules =
+ updatedModules?.filter((moduleId) => {
+ return renewedModules && renewedModules.indexOf(moduleId) < 0;
+ }) ?? [];
if (unacceptedModules.length > 0) {
if (options.warn) {
console.warn(
- "[HMR] The following modules couldn't be hot updated: " +
+ "[Fast refresh] The following modules couldn't be hot updated: " +
'(Full reload needed)\n' +
'This is usually because the modules which have changed ' +
'(and their parents) do not know how to hot reload themselves. ' +
@@ -112,7 +134,9 @@ export const processUpdate = function (hash: string, moduleMap, options) {
' for more details.'
);
unacceptedModules.forEach((moduleId) => {
- console.warn('[HMR] - ' + (moduleMap[moduleId] || moduleId));
+ console.warn(
+ '[Fast refresh] - ' + (moduleMap[moduleId] || moduleId)
+ );
});
}
@@ -120,27 +144,27 @@ export const processUpdate = function (hash: string, moduleMap, options) {
return;
}
- if (options.log) {
- if (!renewedModules || renewedModules.length === 0) {
- console.log('[HMR] Nothing hot updated.');
- } else {
- console.log('[HMR] Updated modules:');
- renewedModules.forEach((moduleId) => {
- console.log('[HMR] - ' + (moduleMap[moduleId] || moduleId));
- });
- }
+ if (!renewedModules || renewedModules.length === 0) {
+ console.log('[Fast refresh] Nothing hot updated.');
+ } else {
+ console.log('[Fast refresh] Updated modules:');
+ renewedModules.forEach((moduleId) => {
+ console.log('[Fast refresh] - ' + (moduleMap[moduleId] || moduleId));
+ });
+ }
- if (upToDate()) {
- console.log('[HMR] App is up to date.');
- }
+ if (upToDate()) {
+ console.log('[Fast refresh] App is up to date.');
}
}
- function handleError(err) {
- if (module.hot.status() in failureStatuses) {
+ function handleError(err: Error) {
+ if ((module.hot?.status() ?? 'nope') in failureStatuses) {
if (options.warn) {
- console.warn('[HMR] Cannot check for update (Full reload needed)');
- console.warn('[HMR] ' + (err.stack || err.message));
+ console.warn(
+ '[Fast refresh] Cannot check for update (Full reload needed)'
+ );
+ console.warn('[Fast refresh] ' + (err.stack || err.message));
}
performReload();
@@ -148,13 +172,15 @@ export const processUpdate = function (hash: string, moduleMap, options) {
}
if (options.warn) {
- console.warn('[HMR] Update check failed: ' + (err.stack || err.message));
+ console.warn(
+ '[Fast refresh] Update check failed: ' + (err.stack || err.message)
+ );
}
}
function performReload() {
if (reload) {
- if (options.warn) console.warn('[HMR] Reloading page');
+ if (options.warn) console.warn('[Fast refresh] Reloading page');
window.location.reload();
}
}
diff --git a/packages/bundler/src/hot-middleware/strip-ansi.ts b/packages/bundler/src/hot-middleware/strip-ansi.ts
new file mode 100644
index 0000000000..1a5fc457a0
--- /dev/null
+++ b/packages/bundler/src/hot-middleware/strip-ansi.ts
@@ -0,0 +1,16 @@
+export const ansiRegex = () => {
+ const pattern = [
+ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
+ '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))',
+ ].join('|');
+
+ return new RegExp(pattern, 'g');
+};
+
+export const stripAnsi = (str: string) => {
+ if (typeof str !== 'string') {
+ throw new TypeError(`Expected a \`string\`, got \`${typeof str}\``);
+ }
+
+ return str.replace(ansiRegex(), '');
+};
diff --git a/packages/bundler/src/hot-middleware/types.ts b/packages/bundler/src/hot-middleware/types.ts
new file mode 100644
index 0000000000..16c7c992c5
--- /dev/null
+++ b/packages/bundler/src/hot-middleware/types.ts
@@ -0,0 +1,39 @@
+import webpack from 'webpack';
+
+export type HotMiddlewareMessage =
+ | {
+ action: 'building';
+ name?: string;
+ }
+ | {
+ action: 'built' | 'sync';
+ name: string;
+ time: number | undefined;
+ errors: unknown[];
+ warnings: unknown[];
+ hash: string | undefined;
+ modules: {
+ [key: string]: string;
+ };
+ };
+
+export const hotMiddlewareOptions = {
+ path: '/__webpack_hmr',
+ timeout: 20 * 1000,
+ overlay: true,
+ reload: false,
+ log: console.log.bind(console),
+ warn: true,
+ name: '',
+ autoConnect: true,
+ overlayStyles: {},
+ overlayWarnings: false,
+ ansiColors: {},
+ heartbeat: 10 * 1000,
+};
+
+export type HotMiddlewareOptions = typeof hotMiddlewareOptions;
+
+export type WebpackStats = ReturnType<webpack.Stats['toJson']>;
+
+export type ModuleMap = {[key: string]: string};
diff --git a/packages/bundler/src/start-server.ts b/packages/bundler/src/start-server.ts
index b825f32bb4..1be52899d4 100644
--- a/packages/bundler/src/start-server.ts
+++ b/packages/bundler/src/start-server.ts
@@ -6,8 +6,6 @@ import os from 'os';
import path from 'path';
import {Internals, WebpackOverrideFn} from 'remotion';
import webpack from 'webpack';
-// @ts-expect-error
-import webpackHotMiddleware from 'webpack-hot-middleware';
import {getDesiredPort} from './get-port';
import {getProjectInfo} from './project-info';
import {isUpdateAvailableWithTimeout} from './update-available';
@@ -20,6 +18,7 @@ import {
launchEditor,
} from './error-overlay/react-overlay/utils/open-in-editor';
import {StackFrame} from './error-overlay/react-overlay/utils/stack-frame';
+import {webpackHotMiddleware} from './hot-middleware';
export const startServer = async (
entry: string,
@@ -55,12 +54,7 @@ export const startServer = async (
app.use(hash, express.static(path.join(process.cwd(), 'public')));
app.use(webpackDevMiddleware(compiler));
- app.use(
- webpackHotMiddleware(compiler, {
- path: '/__webpack_hmr',
- heartbeat: 10 * 1000,
- })
- );
+ app.use(webpackHotMiddleware(compiler));
app.get('/api/update', (req, res) => {
isUpdateAvailableWithTimeout()
diff --git a/packages/bundler/src/webpack-config.ts b/packages/bundler/src/webpack-config.ts
index e55d60f0e4..ccfd7e9d27 100644
--- a/packages/bundler/src/webpack-config.ts
+++ b/packages/bundler/src/webpack-config.ts
@@ -61,7 +61,7 @@ export const webpackConfig = ({
entry: [
require.resolve('./setup-environment'),
environment === 'development'
- ? require.resolve('webpack-hot-middleware/client')
+ ? require.resolve('./hot-middleware/client')
: null,
environment === 'development'
? require.resolve('./fast-refresh/runtime.js')
diff --git a/packages/cli/src/ansi/ansi-regex.ts b/packages/cli/src/ansi/ansi-regex.ts
index 9795fdc4a7..1a5fc457a0 100644
--- a/packages/cli/src/ansi/ansi-regex.ts
+++ b/packages/cli/src/ansi/ansi-regex.ts
@@ -1,8 +1,16 @@
-export default function ansiRegex({onlyFirst = false} = {}) {
+export const ansiRegex = () => {
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))',
].join('|');
- return new RegExp(pattern, onlyFirst ? undefined : 'g');
-}
+ return new RegExp(pattern, 'g');
+};
+
+export const stripAnsi = (str: string) => {
+ if (typeof str !== 'string') {
+ throw new TypeError(`Expected a \`string\`, got \`${typeof str}\``);
+ }
+
+ return str.replace(ansiRegex(), '');
+};
diff --git a/packages/cli/src/ansi/ansi-split.ts b/packages/cli/src/ansi/ansi-split.ts
index c4b9ed4cc6..30af8baaff 100644
--- a/packages/cli/src/ansi/ansi-split.ts
+++ b/packages/cli/src/ansi/ansi-split.ts
@@ -1,4 +1,4 @@
-import ansiRegex from './ansi-regex';
+import {ansiRegex} from './ansi-regex';
export function splitAnsi(str: string): string[] {
const parts = str.match(ansiRegex());
diff --git a/packages/cli/src/editor/components/LoadingIndicator.tsx b/packages/cli/src/editor/components/LoadingIndicator.tsx
index 6926439f89..fbaa7f7ac3 100644
--- a/packages/cli/src/editor/components/LoadingIndicator.tsx
+++ b/packages/cli/src/editor/components/LoadingIndicator.tsx
@@ -9,6 +9,7 @@ const ICON_SIZE = 40;
const label: React.CSSProperties = {
color: '#555',
fontSize: 14,
+ fontFamily: 'sans-serif',
};
const container: React.CSSProperties = {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 221bc44ca9..67ec0d8a61 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -129,7 +129,6 @@ importers:
style-loader: ^2.0.0
typescript: ^4.4.2
webpack: 5.60.0
- webpack-hot-middleware: ^2.25.0
dependencies:
'@jonny/webpack-dev-middleware': [email protected]
css-loader: [email protected]
@@ -145,7 +144,6 @@ importers:
source-map-loader: [email protected]
style-loader: [email protected]
webpack: 5.60.0
- webpack-hot-middleware: 2.25.1
devDependencies:
'@jonny/eslint-config': [email protected][email protected]
'@types/express': 4.17.13
@@ -7803,12 +7801,6 @@ packages:
dependencies:
type-fest: 0.21.3
- /ansi-html-community/0.0.8:
- resolution: {integrity: sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw==}
- engines: {'0': node >= 0.8.0}
- hasBin: true
- dev: false
-
/ansi-html/0.0.7:
resolution: {integrity: sha1-gTWEAhliqenm/QOflA0S9WynhZ4=}
engines: {'0': node >= 0.8.0}
@@ -12752,10 +12744,6 @@ packages:
resolution: {integrity: sha512-8nxjcBcd8wovbeKx7h3wTji4e6+rhaVuPNpMqwWgnHh+N9ToqsCs6XztWRBPQ+UtzsoMAdKZtUENoVzU/EMtZA==}
dev: false
- /html-entities/2.3.2:
- resolution: {integrity: sha512-c3Ab/url5ksaT0WyleslpBEthOzWhrjQbg75y7XUsfSzi3Dgzt0l8w5e7DylRn15MTlMMD58dTfzddNS2kcAjQ==}
- dev: false
-
/html-escaper/2.0.2:
resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
@@ -22285,15 +22273,6 @@ packages:
yargs: 13.3.2
dev: false
- /webpack-hot-middleware/2.25.1:
- resolution: {integrity: sha512-Koh0KyU/RPYwel/khxbsDz9ibDivmUbrRuKSSQvW42KSDdO4w23WI3SkHpSUKHE76LrFnnM/L7JCrpBwu8AXYw==}
- dependencies:
- ansi-html-community: 0.0.8
- html-entities: 2.3.2
- querystring: 0.2.1
- strip-ansi: 6.0.1
- dev: false
-
/webpack-log/2.0.0:
resolution: {integrity: sha512-cX8G2vR/85UYG59FgkoMamwHUIkSSlV3bBMRsbxVXVUk2j6NleCKjQ/WE9eYg9WY4w25O9w8wKP4rzNZFmUcUg==}
engines: {node: '>= 6'}