Skip to content

πŸŽ₯ Make videos programmatically with React

Suppress webpack rebuild when updating default props

Jonny Burgerfec90504253a
diff --git a/packages/bundler/src/index.ts b/packages/bundler/src/index.ts
index 7cbd0de232..338a6ca076 100644
--- a/packages/bundler/src/index.ts
+++ b/packages/bundler/src/index.ts
@@ -2,6 +2,7 @@ import {findClosestFolderWithItem, getConfig, internalBundle} from './bundle';
import {indexHtml} from './index-html';
import {readRecursively} from './read-recursively';
import {createRspackCompiler, rspackConfig} from './rspack-config';
+import {WatchIgnoreNextChangePlugin} from './watch-ignore-next-change-plugin';
import {cacheExists, clearCache} from './webpack-cache';
import {webpackConfig} from './webpack-config';
import esbuild = require('esbuild');
@@ -29,4 +30,5 @@ export {
MandatoryLegacyBundleOptions,
} from './bundle';
export {WebpackConfiguration, WebpackOverrideFn} from './webpack-config';
+export {WatchIgnoreNextChangePlugin};
export {webpack};
diff --git a/packages/bundler/src/rspack-config.ts b/packages/bundler/src/rspack-config.ts
index 5ba116e888..dc480b3520 100644
--- a/packages/bundler/src/rspack-config.ts
+++ b/packages/bundler/src/rspack-config.ts
@@ -29,6 +29,7 @@ export const rspackConfig = async ({
experimentalClientSideRenderingEnabled,
experimentalVisualModeEnabled,
askAIEnabled,
+ extraPlugins,
}: {
entry: string;
userDefinedComponent: string;
@@ -45,6 +46,8 @@ export const rspackConfig = async ({
askAIEnabled: boolean;
experimentalClientSideRenderingEnabled: boolean;
experimentalVisualModeEnabled: boolean;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ extraPlugins?: any[];
}): Promise<[string, RspackConfiguration]> => {
let lastProgress = 0;
@@ -118,6 +121,7 @@ export const rspackConfig = async ({
new ReactRefreshPlugin({overlay: false}),
new rspack.HotModuleReplacementPlugin(),
define,
+ ...(extraPlugins ?? []),
]
: [
new ProgressPlugin((p: number) => {
diff --git a/packages/bundler/src/watch-ignore-next-change-plugin.ts b/packages/bundler/src/watch-ignore-next-change-plugin.ts
new file mode 100644
index 0000000000..1ca38014d2
--- /dev/null
+++ b/packages/bundler/src/watch-ignore-next-change-plugin.ts
@@ -0,0 +1,357 @@
+import path from 'node:path';
+import type {Compiler} from 'webpack';
+
+type TimeInfoEntry =
+ | {
+ safeTime: number;
+ timestamp?: number;
+ accuracy?: number;
+ }
+ | 'ignore'
+ | null;
+
+type WatchCallback = (
+ err: null | Error,
+ fileTimestamps?: Map<string, TimeInfoEntry>,
+ dirTimestamps?: Map<string, TimeInfoEntry>,
+ changedFiles?: Set<string>,
+ removedFiles?: Set<string>,
+) => void;
+
+type CallbackUndelayed = (fileName: string, changeTime: number) => void;
+
+type Watcher = {
+ close: () => void;
+ pause: () => void;
+ getAggregatedRemovals?: () => Set<string>;
+ getAggregatedChanges?: () => Set<string>;
+ getFileTimeInfoEntries: () => Map<string, TimeInfoEntry>;
+ getContextTimeInfoEntries: () => Map<string, TimeInfoEntry>;
+ getInfo?: () => {
+ changes: Set<string>;
+ removals: Set<string>;
+ fileTimeInfoEntries: Map<string, TimeInfoEntry>;
+ contextTimeInfoEntries: Map<string, TimeInfoEntry>;
+ };
+};
+
+// NodeWatchFileSystem has a .watcher (Watchpack) with EventEmitter methods
+type NodeWatchFileSystem = {
+ watcher: {
+ once: (event: string, listener: (...args: unknown[]) => void) => void;
+ pause: () => void;
+ paused: boolean;
+ };
+ inputFileSystem: {
+ purge?: (item: string) => void;
+ };
+ watch: (
+ files: Iterable<string>,
+ directories: Iterable<string>,
+ missing: Iterable<string>,
+ startTime: number,
+ options: Record<string, unknown>,
+ callback: WatchCallback,
+ callbackUndelayed: CallbackUndelayed,
+ ) => Watcher;
+};
+
+export class WatchIgnoreNextChangePlugin {
+ private filesToIgnore = new Set<string>();
+ private dirsToIgnore = new Set<string>();
+ private snapshotFileTimestamps = new Map<string, TimeInfoEntry>();
+ private snapshotDirTimestamps = new Map<string, TimeInfoEntry>();
+ private currentWatcher: Watcher | null = null;
+
+ ignoreNextChange(file: string): void {
+ this.filesToIgnore.add(file);
+ const dir = path.dirname(file);
+ this.dirsToIgnore.add(dir);
+
+ // Snapshot current timestamps from the watcher BEFORE the file is written
+ if (this.currentWatcher) {
+ const fileEntries = this.currentWatcher.getFileTimeInfoEntries();
+ const fileTs = fileEntries.get(file);
+ if (fileTs !== undefined) {
+ this.snapshotFileTimestamps.set(file, fileTs);
+ }
+
+ const dirEntries = this.currentWatcher.getContextTimeInfoEntries();
+ const dirTs = dirEntries.get(dir);
+ if (dirTs !== undefined) {
+ this.snapshotDirTimestamps.set(dir, dirTs);
+ }
+ }
+ }
+
+ unignoreNextChange(file: string): void {
+ this.filesToIgnore.delete(file);
+ const dir = path.dirname(file);
+ this.dirsToIgnore.delete(dir);
+ this.snapshotFileTimestamps.delete(file);
+ this.snapshotDirTimestamps.delete(dir);
+ }
+
+ apply(compiler: Compiler): void {
+ compiler.hooks.afterEnvironment.tap('WatchIgnoreNextChangePlugin', () => {
+ const wfs = compiler.watchFileSystem as unknown as NodeWatchFileSystem;
+ if (!wfs?.watch) {
+ return;
+ }
+
+ const originalWatch = wfs.watch.bind(wfs);
+
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ const self = this;
+
+ wfs.watch = (
+ files,
+ directories,
+ missing,
+ startTime,
+ options,
+ callback,
+ callbackUndelayed,
+ ) => {
+ const wrappedCallbackUndelayed: CallbackUndelayed = (
+ fileName,
+ changeTime,
+ ) => {
+ if (
+ self.filesToIgnore.has(fileName) ||
+ self.dirsToIgnore.has(fileName)
+ ) {
+ return;
+ }
+
+ callbackUndelayed(fileName, changeTime);
+ };
+
+ const wrappedCallback: WatchCallback = (
+ err,
+ fileTimestamps,
+ dirTimestamps,
+ changedFiles,
+ removedFiles,
+ ) => {
+ const hasIgnoredFiles = self.filesToIgnore.size > 0;
+
+ if (fileTimestamps) {
+ for (const file of [...self.filesToIgnore]) {
+ const wasInChanged = changedFiles?.has(file) ?? false;
+ if (wasInChanged) {
+ changedFiles!.delete(file);
+ }
+
+ const prev = self.snapshotFileTimestamps.get(file);
+ if (prev !== undefined) {
+ fileTimestamps.set(file, prev);
+ }
+
+ if (wasInChanged) {
+ self.filesToIgnore.delete(file);
+ self.snapshotFileTimestamps.delete(file);
+ }
+ }
+ }
+
+ if (dirTimestamps) {
+ for (const dir of [...self.dirsToIgnore]) {
+ const wasInChanged = changedFiles?.has(dir) ?? false;
+ if (wasInChanged) {
+ changedFiles!.delete(dir);
+ }
+
+ const prev = self.snapshotDirTimestamps.get(dir);
+ if (prev !== undefined) {
+ dirTimestamps.set(dir, prev);
+ }
+
+ if (wasInChanged) {
+ self.dirsToIgnore.delete(dir);
+ self.snapshotDirTimestamps.delete(dir);
+ }
+ }
+ }
+
+ if (removedFiles) {
+ for (const file of self.filesToIgnore) {
+ removedFiles.delete(file);
+ }
+
+ for (const dir of self.dirsToIgnore) {
+ removedFiles.delete(dir);
+ }
+ }
+
+ const remainingChanges = changedFiles?.size ?? 0;
+ const remainingRemovals = removedFiles?.size ?? 0;
+
+ if (
+ hasIgnoredFiles &&
+ remainingChanges === 0 &&
+ remainingRemovals === 0
+ ) {
+ // Don't call the callback β€” that would trigger _invalidate() β†’ compile().
+ // Instead, re-register the watchpack listeners and unpause,
+ // so the watch loop stays alive for future changes.
+ // NodeWatchFileSystem uses:
+ // this.watcher.once("change", callbackUndelayed)
+ // this.watcher.once("aggregated", (changes, removals) => { this.watcher.pause(); callback(...) })
+ // After "aggregated" fires, the watcher is paused and the .once listeners are consumed.
+ // We need to restore them.
+ const watchpack = wfs.watcher;
+ if (watchpack) {
+ watchpack.once(
+ 'change',
+ wrappedCallbackUndelayed as (...args: unknown[]) => void,
+ );
+ watchpack.once('aggregated', (...args: unknown[]) => {
+ const changes = args[0] as Set<string>;
+ const removals = args[1] as Set<string>;
+ watchpack.pause();
+ const fs = wfs.inputFileSystem;
+ if (fs?.purge) {
+ for (const item of changes) {
+ fs.purge(item);
+ }
+
+ for (const item of removals) {
+ fs.purge(item);
+ }
+ }
+
+ const fetchedFileTimestamps = new Map<string, TimeInfoEntry>();
+ const fetchedContextTimestamps = new Map<
+ string,
+ TimeInfoEntry
+ >();
+ (
+ watchpack as unknown as {
+ collectTimeInfoEntries: (
+ a: Map<string, TimeInfoEntry>,
+ b: Map<string, TimeInfoEntry>,
+ ) => void;
+ }
+ ).collectTimeInfoEntries(
+ fetchedFileTimestamps,
+ fetchedContextTimestamps,
+ );
+
+ wrappedCallback(
+ null,
+ fetchedFileTimestamps,
+ fetchedContextTimestamps,
+ changes,
+ removals,
+ );
+ });
+ watchpack.paused = false;
+ } else {
+ callback(
+ err,
+ fileTimestamps,
+ dirTimestamps,
+ changedFiles,
+ removedFiles,
+ );
+ }
+
+ return;
+ }
+
+ callback(
+ err,
+ fileTimestamps,
+ dirTimestamps,
+ changedFiles,
+ removedFiles,
+ );
+ };
+
+ const watcher = originalWatch(
+ files,
+ directories,
+ missing,
+ startTime,
+ options,
+ wrappedCallback,
+ wrappedCallbackUndelayed,
+ );
+
+ self.currentWatcher = watcher;
+
+ const originalGetFileTimeInfoEntries =
+ watcher.getFileTimeInfoEntries.bind(watcher);
+ watcher.getFileTimeInfoEntries = () => {
+ const entries = originalGetFileTimeInfoEntries();
+ for (const file of self.filesToIgnore) {
+ const prev = self.snapshotFileTimestamps.get(file);
+ if (prev !== undefined) {
+ entries.set(file, prev);
+ }
+ }
+
+ return entries;
+ };
+
+ const originalGetContextTimeInfoEntries =
+ watcher.getContextTimeInfoEntries.bind(watcher);
+ watcher.getContextTimeInfoEntries = () => {
+ const entries = originalGetContextTimeInfoEntries();
+ for (const dir of self.dirsToIgnore) {
+ const prev = self.snapshotDirTimestamps.get(dir);
+ if (prev !== undefined) {
+ entries.set(dir, prev);
+ }
+ }
+
+ return entries;
+ };
+
+ if (watcher.getInfo) {
+ const originalGetInfo = watcher.getInfo.bind(watcher);
+ watcher.getInfo = () => {
+ const info = originalGetInfo();
+ for (const file of self.filesToIgnore) {
+ info.changes.delete(file);
+ const prev = self.snapshotFileTimestamps.get(file);
+ if (prev !== undefined) {
+ info.fileTimeInfoEntries.set(file, prev);
+ }
+ }
+
+ for (const dir of self.dirsToIgnore) {
+ info.changes.delete(dir);
+ const prev = self.snapshotDirTimestamps.get(dir);
+ if (prev !== undefined) {
+ info.contextTimeInfoEntries.set(dir, prev);
+ }
+ }
+
+ return info;
+ };
+ }
+
+ if (watcher.getAggregatedChanges) {
+ const originalGetAggregatedChanges =
+ watcher.getAggregatedChanges.bind(watcher);
+ watcher.getAggregatedChanges = () => {
+ const changes = originalGetAggregatedChanges();
+ for (const file of self.filesToIgnore) {
+ changes.delete(file);
+ }
+
+ for (const dir of self.dirsToIgnore) {
+ changes.delete(dir);
+ }
+
+ return changes;
+ };
+ }
+
+ return watcher;
+ };
+ });
+ }
+}
diff --git a/packages/bundler/src/webpack-config.ts b/packages/bundler/src/webpack-config.ts
index ef65c00dd1..e999da8c6a 100644
--- a/packages/bundler/src/webpack-config.ts
+++ b/packages/bundler/src/webpack-config.ts
@@ -43,6 +43,7 @@ export const webpackConfig = async ({
experimentalClientSideRenderingEnabled,
experimentalVisualModeEnabled,
askAIEnabled,
+ extraPlugins,
}: {
entry: string;
userDefinedComponent: string;
@@ -59,6 +60,7 @@ export const webpackConfig = async ({
askAIEnabled: boolean;
experimentalClientSideRenderingEnabled: boolean;
experimentalVisualModeEnabled: boolean;
+ extraPlugins?: webpack.WebpackPluginInstance[];
}): Promise<[string, WebpackConfiguration]> => {
const esbuildLoaderOptions: LoaderOptions = {
target: 'chrome85',
@@ -108,6 +110,7 @@ export const webpackConfig = async ({
new AllowOptionalDependenciesPlugin(),
new AllowDependencyExpressionPlugin(),
new IgnorePackFileCacheWarningsPlugin(),
+ ...(extraPlugins ?? []),
]
: [
new ProgressPlugin((p) => {
diff --git a/packages/studio-server/src/preview-server/routes/update-default-props.ts b/packages/studio-server/src/preview-server/routes/update-default-props.ts
index ffb16e4a31..634ad00f43 100644
--- a/packages/studio-server/src/preview-server/routes/update-default-props.ts
+++ b/packages/studio-server/src/preview-server/routes/update-default-props.ts
@@ -12,6 +12,7 @@ import type {ApiHandler} from '../api-types';
import {suppressHmrForFile} from '../hmr-suppression';
import {getProjectInfo} from '../project-info';
import {pushToUndoStack, suppressUndoStackInvalidation} from '../undo-stack';
+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';
import {checkIfTypeScriptFile} from './can-update-default-props';
import {warnAboutPrettierOnce} from './log-update';
@@ -43,6 +44,7 @@ export const updateDefaultPropsHandler: ApiHandler<
pushToUndoStack(projectInfo.rootFile, fileContents, logLevel);
suppressUndoStackInvalidation(projectInfo.rootFile);
suppressHmrForFile(projectInfo.rootFile);
+ suppressBundlerUpdateForFile(projectInfo.rootFile);
writeFileAndNotifyFileWatchers(projectInfo.rootFile, output);
const fileRelativeToRoot = path.relative(
diff --git a/packages/studio-server/src/preview-server/start-server.ts b/packages/studio-server/src/preview-server/start-server.ts
index c26009f9bf..a234247967 100644
--- a/packages/studio-server/src/preview-server/start-server.ts
+++ b/packages/studio-server/src/preview-server/start-server.ts
@@ -1,7 +1,11 @@
import type {IncomingMessage} from 'node:http';
import http from 'node:http';
import type {WebpackOverrideFn} from '@remotion/bundler';
-import {BundlerInternals, webpack} from '@remotion/bundler';
+import {
+ BundlerInternals,
+ WatchIgnoreNextChangePlugin,
+ webpack,
+} from '@remotion/bundler';
import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import type {
@@ -17,6 +21,7 @@ import {webpackHotMiddleware} from './hot-middleware';
import type {LiveEventsServer} from './live-events';
import {makeLiveEventsRouter} from './live-events';
import {getRedoStack, getUndoStack} from './undo-stack';
+import {setWatchIgnoreNextChangePlugin} from './watch-ignore-next-change';
export type StartServerResult =
| {
@@ -81,6 +86,8 @@ export const startServer = async (options: {
return detection.type === 'match' ? 'stop' : 'continue';
};
+ const watchIgnorePlugin = new WatchIgnoreNextChangePlugin();
+
const configArgs = {
entry: options.entry,
userDefinedComponent: options.userDefinedComponent,
@@ -96,6 +103,7 @@ export const startServer = async (options: {
poll: options.poll,
bufferStateDelayInMilliseconds: options.bufferStateDelayInMilliseconds,
askAIEnabled: options.askAIEnabled,
+ extraPlugins: [watchIgnorePlugin],
};
let compiler: webpack.Compiler;
@@ -109,6 +117,8 @@ export const startServer = async (options: {
compiler = webpack(webpackConf);
}
+ setWatchIgnoreNextChangePlugin(watchIgnorePlugin);
+
const wdmMiddleware = wdm(compiler, options.logLevel);
const whm = webpackHotMiddleware(compiler, options.logLevel);
diff --git a/packages/studio-server/src/preview-server/watch-ignore-next-change.ts b/packages/studio-server/src/preview-server/watch-ignore-next-change.ts
new file mode 100644
index 0000000000..bc6e6293e4
--- /dev/null
+++ b/packages/studio-server/src/preview-server/watch-ignore-next-change.ts
@@ -0,0 +1,13 @@
+import type {WatchIgnoreNextChangePlugin} from '@remotion/bundler';
+
+let currentPlugin: WatchIgnoreNextChangePlugin | null = null;
+
+export const setWatchIgnoreNextChangePlugin = (
+ plugin: WatchIgnoreNextChangePlugin,
+): void => {
+ currentPlugin = plugin;
+};
+
+export const suppressBundlerUpdateForFile = (absolutePath: string): void => {
+ currentPlugin?.ignoreNextChange(absolutePath);
+};