Skip to content

🎥 Make videos programmatically with React

@remotion/browser-bundler: Simplify projects and compile Player edits automatically

Jonny Burger24a92211e901
diff --git a/packages/browser-bundler/src/browser-bundler-worker.ts b/packages/browser-bundler/src/browser-bundler-worker.ts
index d222e79db5..9bbfef1c3c 100644
--- a/packages/browser-bundler/src/browser-bundler-worker.ts
+++ b/packages/browser-bundler/src/browser-bundler-worker.ts
@@ -1,6 +1,7 @@
import {
createBrowserCompiler,
type BrowserCompiler,
+ type BrowserCompilerProject,
} from './create-browser-compiler';
import {createBrowserDependencyPlugin} from './dependency-resolution';
import {BrowserBundlerError, serializeCompilerError} from './errors';
@@ -8,7 +9,6 @@ import {makeBrowserHttpClient} from './http-client';
import type {
BrowserBundlerWorkerRequest,
BrowserBundlerWorkerResponse,
- VirtualProject,
} from './types';
import {normalizeVirtualPath} from './virtual-project';
@@ -26,7 +26,7 @@ const sharedModules = [
];
let compiler: BrowserCompiler | null = null;
-let previousProject: VirtualProject | null = null;
+let previousProject: BrowserCompilerProject | null = null;
let queue: Promise<void> = Promise.resolve();
const postResponse = (response: BrowserBundlerWorkerResponse) => {
@@ -39,7 +39,10 @@ self.addEventListener(
const request = event.data;
queue = queue.then(async () => {
try {
- const {project} = request;
+ const project: BrowserCompilerProject = {
+ ...request.project,
+ rootDir: '/',
+ };
if (
compiler &&
(previousProject?.rootDir !== project.rootDir ||
diff --git a/packages/browser-bundler/src/compiler.ts b/packages/browser-bundler/src/compiler.ts
index f9f79831db..31b26881f1 100644
--- a/packages/browser-bundler/src/compiler.ts
+++ b/packages/browser-bundler/src/compiler.ts
@@ -1,6 +1,7 @@
export {
createBrowserCompiler,
type BrowserCompiler,
+ type BrowserCompilerProject,
type BrowserCompilerResult,
} from './create-browser-compiler';
export {createBrowserDependencyPlugin} from './dependency-resolution';
diff --git a/packages/browser-bundler/src/create-browser-compiler.ts b/packages/browser-bundler/src/create-browser-compiler.ts
index 3138d31cb0..6d871cffae 100644
--- a/packages/browser-bundler/src/create-browser-compiler.ts
+++ b/packages/browser-bundler/src/create-browser-compiler.ts
@@ -7,6 +7,10 @@ import {
normalizeVirtualPath,
} from './virtual-project';
+export type BrowserCompilerProject = VirtualProject & {
+ rootDir: string;
+};
+
export type BrowserCompilerResult = {
bundle: string | null;
assets: {name: string; content: string}[];
@@ -18,7 +22,7 @@ export type BrowserCompilerResult = {
};
export type BrowserCompiler = {
- compile: (project: VirtualProject) => Promise<BrowserCompilerResult>;
+ compile: (project: BrowserCompilerProject) => Promise<BrowserCompilerResult>;
dispose: () => Promise<void>;
};
@@ -42,7 +46,7 @@ export const createBrowserCompiler = async ({
configure,
onProgress,
}: {
- project: VirtualProject;
+ project: BrowserCompilerProject;
virtualFiles: Record<string, string>;
configure: (rspack: typeof RspackBrowser) => RspackBrowser.Configuration;
onProgress: ((progress: BrowserBundlerProgress) => void) | null;
diff --git a/packages/browser-bundler/src/test/virtual-project.test.ts b/packages/browser-bundler/src/test/virtual-project.test.ts
index 22319321f8..834c4d5825 100644
--- a/packages/browser-bundler/src/test/virtual-project.test.ts
+++ b/packages/browser-bundler/src/test/virtual-project.test.ts
@@ -1,35 +1,35 @@
import {expect, test} from 'bun:test';
+import type {VirtualProject} from '../types';
import {
getVirtualProjectChanges,
getVirtualProjectFiles,
} from '../virtual-project';
test('source snapshots distinguish added, edited, removed and unchanged virtual files', () => {
- const project = {
- rootDir: '/project',
- entryPoint: '/project/index.ts',
+ const project: VirtualProject = {
+ entryPoint: 'src/index.ts',
files: {
- 'project/index.ts': "import './Video';",
- '/project/Video.tsx': 'export const Video = () => null;',
- '/project/removed.ts': 'export const unused = true;',
+ 'src/index.ts': "import './Video';",
+ '/src/Video.tsx': 'export const Video = () => null;',
+ '/src/removed.ts': 'export const unused = true;',
},
};
const previous = getVirtualProjectFiles(project);
const next = getVirtualProjectFiles({
...project,
files: {
- '/project/index.ts': "import './Video';",
- 'project/Video.tsx': 'export const Video = () => <div />;',
- '/project/added.ts': 'export const title = "New";',
+ '/src/index.ts': "import './Video';",
+ 'src/Video.tsx': 'export const Video = () => <div />;',
+ '/src/added.ts': 'export const title = "New";',
},
});
expect(getVirtualProjectChanges({previous, next})).toEqual({
- modified: ['/project/Video.tsx', '/project/added.ts'],
- removed: ['/project/removed.ts'],
+ modified: ['/src/Video.tsx', '/src/added.ts'],
+ removed: ['/src/removed.ts'],
});
expect(getVirtualProjectChanges({previous: next, next})).toEqual({
modified: [],
removed: [],
});
- expect(project.files['project/index.ts']).toBe("import './Video';");
+ expect(project.files['src/index.ts']).toBe("import './Video';");
});
diff --git a/packages/browser-bundler/src/types.ts b/packages/browser-bundler/src/types.ts
index 0b337fcbdf..671cff8884 100644
--- a/packages/browser-bundler/src/types.ts
+++ b/packages/browser-bundler/src/types.ts
@@ -1,5 +1,4 @@
export type VirtualProject = {
- rootDir: string;
entryPoint: string;
files: Record<string, string>;
};
diff --git a/packages/browser-studio/src/types.ts b/packages/browser-studio/src/types.ts
index 1c2638dd43..e090d53a3c 100644
--- a/packages/browser-studio/src/types.ts
+++ b/packages/browser-studio/src/types.ts
@@ -1,4 +1,4 @@
-import type {VirtualProject as SourceProject} from '@remotion/browser-bundler';
+import type {BrowserCompilerProject as SourceProject} from '@remotion/browser-bundler/compiler';
import type {StudioElementPayload} from '@remotion/studio-protocol';
import type {HotMiddlewareMessage} from '@remotion/studio-shared';
diff --git a/packages/docs/docs/browser-bundler/create-browser-bundler.mdx b/packages/docs/docs/browser-bundler/create-browser-bundler.mdx
index e410655655..6f83c25f81 100644
--- a/packages/docs/docs/browser-bundler/create-browser-bundler.mdx
+++ b/packages/docs/docs/browser-bundler/create-browser-bundler.mdx
@@ -119,21 +119,17 @@ Pending `bundle()` calls reject, and further calls to `bundle()` on this instanc
An object describing source files in memory. Import the `VirtualProject` type from `@remotion/browser-bundler`.
-### rootDir
-
-The virtual project's root directory, for example `'/project'`. Use forward-slash paths.
-
### entryPoint
-The virtual entry file, for example `'/project/src/index.ts'`. It must be included in `files`.
+The project-relative entry file, for example `'src/index.ts'`. It must be included in `files`.
Use an ordinary Remotion entry point that calls [`registerRoot()`](/docs/register-root) if you will execute the result with [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle).
-Keep `rootDir` and `entryPoint` unchanged across source edits to reuse the compiler. Changing either starts a new compiler for the new project.
+Keep `entryPoint` unchanged across source edits to reuse the compiler. Changing it starts a new compiler for the new project.
### files
-A `Record<string, string>` mapping virtual file paths to their source text. Use complete paths such as `'/project/src/Root.tsx'`, not paths relative to `rootDir`.
+A `Record<string, string>` mapping project-relative file paths to their source text, for example `'src/Root.tsx'`. Use forward slashes and a conventional Remotion directory structure; no enclosing directory prefix is needed.
This is a source snapshot, not a persistent filesystem. Do not include binary media or expect files under `public/` to be served as assets.
diff --git a/packages/docs/docs/browser-bundler/index.mdx b/packages/docs/docs/browser-bundler/index.mdx
index e145a326ba..d9353a5e8e 100644
--- a/packages/docs/docs/browser-bundler/index.mdx
+++ b/packages/docs/docs/browser-bundler/index.mdx
@@ -124,15 +124,14 @@ import {Player} from '@remotion/player';
import {useEffect, useState} from 'react';
const project: VirtualProject = {
- rootDir: '/project',
- entryPoint: '/project/src/index.ts',
+ entryPoint: 'src/index.ts',
files: {
- '/project/src/index.ts': `
+ 'src/index.ts': `
import {registerRoot} from 'remotion';
import {Root} from './Root';
registerRoot(Root);
`,
- '/project/src/Root.tsx': `
+ 'src/Root.tsx': `
import {AbsoluteFill, Composition, useCurrentFrame} from 'remotion';
const Video = ({message}: {message: string}) => {
@@ -233,13 +232,13 @@ export const BrowserBundlerPreview = () => {
Pass the returned `component` to [`<Player>`](/docs/player/player), not the registered root or `<Composition>` itself. Pass `props` and the resolved dimensions, frame rate, and duration alongside it. [`getBrowserComposition()`](/docs/browser-bundler/get-browser-composition) merges default and input props and runs [`calculateMetadata()`](/docs/calculate-metadata) when provided.
-This example compiles once and disposes its worker. For editing, keep the bundler alive, submit a new complete snapshot for each compilation, then load and resolve the new bundle before updating your Player.
+This example compiles once and disposes its worker. For editing, keep the bundler alive and submit a new complete snapshot when the source changes. Load and resolve the new bundle before updating your Player. Keep the last successful preview visible while compiling, and discard results superseded by newer edits.
## Scope and limitations
### Source snapshots
-A [`VirtualProject`](/docs/browser-bundler/create-browser-bundler#virtualproject) contains source file paths and text. You own editing, history, saving, and restoring snapshots. The package does not provide filesystem persistence or an installation UI for npm packages.
+A [`VirtualProject`](/docs/browser-bundler/create-browser-bundler#virtualproject) contains project-relative source file paths, such as `src/index.ts` and `src/Root.tsx`, and their text. You own editing, history, saving, and restoring snapshots. The package does not provide filesystem persistence or an installation UI for npm packages.
### Dependencies
diff --git a/packages/player-example/e2e/browser-bundler.test.ts b/packages/player-example/e2e/browser-bundler.test.ts
index 05171e654f..f9cf42ee15 100644
--- a/packages/player-example/e2e/browser-bundler.test.ts
+++ b/packages/player-example/e2e/browser-bundler.test.ts
@@ -1,7 +1,7 @@
import {expect, test} from '@playwright/test';
import {VERSION} from 'remotion/version';
-test('compiles a virtual root, plays its composition, imports a dependency and recovers from errors', async ({
+test('compiles conventional source paths, plays its composition and automatically recompiles edits', async ({
page,
}) => {
const pageErrors: string[] = [];
@@ -49,7 +49,6 @@ test('compiles a virtual root, plays its composition, imports a dependency and r
'<Circle radius={40} fill="red" role="img" aria-label="Bundled circle" />',
)}`,
);
- await page.getByRole('button', {name: 'Compile', exact: true}).click();
expect(new URL((await dependencyRequest).url()).searchParams.has('dev')).toBe(
false,
);
@@ -64,15 +63,20 @@ test('compiles a virtual root, plays its composition, imports a dependency and r
).toBeVisible();
await editor.fill("import {Broken from 'remotion';");
- await page.getByRole('button', {name: 'Compile', exact: true}).click();
const compilationError = page
.getByRole('alert')
.filter({hasText: 'Rspack compilation failed'});
await expect(compilationError).toBeVisible();
await expect(compilationError).toContainText('Video.tsx');
+ await expect(
+ composition.getByRole('heading', {
+ name: 'COMPILED IN THE BROWSER',
+ exact: true,
+ }),
+ ).toBeVisible();
+ await editor.fill(original.replace('{title}', '{title + " - intermediate"}'));
await editor.fill(original);
- await page.getByRole('button', {name: 'Compile', exact: true}).click();
await expect(
composition.getByRole('heading', {
name: 'Compiled in the browser',
diff --git a/packages/player-example/src/BrowserBundlerExample.tsx b/packages/player-example/src/BrowserBundlerExample.tsx
index 6828a52eba..ea3d7aa2f0 100644
--- a/packages/player-example/src/BrowserBundlerExample.tsx
+++ b/packages/player-example/src/BrowserBundlerExample.tsx
@@ -36,14 +36,13 @@ export const Video: React.FC<{title: string; accent: string}> = ({title, accent}
`;
const project: VirtualProject = {
- rootDir: '/browser-demo',
- entryPoint: '/browser-demo/src/index.ts',
+ entryPoint: 'src/index.ts',
files: {
- '/browser-demo/src/index.ts': `import {registerRoot} from 'remotion';
+ 'src/index.ts': `import {registerRoot} from 'remotion';
import {Root} from './Root';
registerRoot(Root);
`,
- '/browser-demo/src/Root.tsx': `import React from 'react';
+ 'src/Root.tsx': `import React from 'react';
import {Composition, Folder} from 'remotion';
import {Video} from './Video';
@@ -65,8 +64,8 @@ export const Root = () => (
</Folder>
);
`,
- '/browser-demo/src/Video.tsx': initialSource,
- '/browser-demo/src/Orb.tsx': `import React from 'react';
+ 'src/Video.tsx': initialSource,
+ 'src/Orb.tsx': `import React from 'react';
import {useCurrentFrame} from 'remotion';
export const Orb: React.FC<{accent: string}> = ({accent}) => {
@@ -92,15 +91,15 @@ const getCompilationErrorMessage = (error: unknown): string => {
type CompilationState =
| {type: 'loading'}
| {type: 'error'; message: string}
- | {
- type: 'ready';
- composition: BrowserComposition;
- revision: number;
- };
+ | {type: 'ready'};
export const BrowserBundlerExample: React.FC = () => {
const [source, setSource] = useState(initialSource);
const [state, setState] = useState<CompilationState>({type: 'loading'});
+ const [preview, setPreview] = useState<{
+ composition: BrowserComposition;
+ revision: number;
+ } | null>(null);
const [progress, setProgress] = useState<string | null>(null);
const [warnings, setWarnings] = useState<string[]>([]);
const bundlerRef = useRef<ReturnType<typeof createBrowserBundler> | null>(
@@ -108,6 +107,7 @@ export const BrowserBundlerExample: React.FC = () => {
);
const requestId = useRef(0);
const abortRef = useRef<AbortController | null>(null);
+ const compilationQueue = useRef<Promise<void>>(Promise.resolve());
const compile = useCallback(async (videoSource: string) => {
const bundler = bundlerRef.current;
@@ -123,43 +123,51 @@ export const BrowserBundlerExample: React.FC = () => {
setWarnings([]);
setProgress(null);
- try {
- const bundle = await bundler.bundle({
- project: {
- ...project,
- files: {
- ...project.files,
- '/browser-demo/src/Video.tsx': videoSource,
- },
- },
- });
+ compilationQueue.current = compilationQueue.current.then(async () => {
if (controller.signal.aborted || revision !== requestId.current) {
return;
}
- setWarnings(bundle.warnings);
- const root = loadBrowserBundle({bundle});
- const composition = await getBrowserComposition({
- root,
- compositionId: 'BrowserDemo',
- inputProps: {},
- signal: controller.signal,
- });
- if (controller.signal.aborted || revision !== requestId.current) {
- return;
- }
+ try {
+ const bundle = await bundler.bundle({
+ project: {
+ ...project,
+ files: {
+ ...project.files,
+ 'src/Video.tsx': videoSource,
+ },
+ },
+ });
+ if (controller.signal.aborted || revision !== requestId.current) {
+ return;
+ }
- setState({type: 'ready', composition, revision});
- } catch (error) {
- if (controller.signal.aborted || revision !== requestId.current) {
- return;
- }
+ setWarnings(bundle.warnings);
+ const root = loadBrowserBundle({bundle});
+ const composition = await getBrowserComposition({
+ root,
+ compositionId: 'BrowserDemo',
+ inputProps: {},
+ signal: controller.signal,
+ });
+ if (controller.signal.aborted || revision !== requestId.current) {
+ return;
+ }
- setState({
- type: 'error',
- message: getCompilationErrorMessage(error),
- });
- }
+ setPreview({composition, revision});
+ setState({type: 'ready'});
+ } catch (error) {
+ if (controller.signal.aborted || revision !== requestId.current) {
+ return;
+ }
+
+ setState({
+ type: 'error',
+ message: getCompilationErrorMessage(error),
+ });
+ }
+ });
+ await compilationQueue.current;
}, []);
useEffect(() => {
@@ -221,22 +229,21 @@ export const BrowserBundlerExample: React.FC = () => {
default props, and calculated metadata in a Player.
</p>
<p>
- Edit the source and compile again. Only run code you trust: the compiled
+ Edits recompile automatically. Only run code you trust: the compiled
code runs in this page, not in a sandbox.
</p>
- <form
- onSubmit={(event) => {
- event.preventDefault();
- void compile(source);
- }}
- >
+ <div>
<label htmlFor="browser-video-source">
<strong>Video.tsx source</strong>
</label>
<textarea
id="browser-video-source"
value={source}
- onChange={(event) => setSource(event.target.value)}
+ onChange={(event) => {
+ const nextSource = event.target.value;
+ setSource(nextSource);
+ void compile(nextSource);
+ }}
rows={17}
spellCheck={false}
style={{
@@ -250,8 +257,7 @@ export const BrowserBundlerExample: React.FC = () => {
width: '100%',
}}
/>
- <button type="submit">Compile</button>
- </form>
+ </div>
<p role="status" aria-live="polite">
{state.type === 'loading'
? (progress ?? 'Compiling the virtual project...')
@@ -276,21 +282,21 @@ export const BrowserBundlerExample: React.FC = () => {
{state.message}
</pre>
) : null}
- {state.type === 'ready' ? (
+ {preview ? (
<section aria-label="Compiled composition">
<p>
- {state.composition.width} x {state.composition.height} /{' '}
- {state.composition.fps} fps / {state.composition.durationInFrames}{' '}
- frames
+ {preview.composition.width} x {preview.composition.height} /{' '}
+ {preview.composition.fps} fps /{' '}
+ {preview.composition.durationInFrames} frames
</p>
<Player
- key={state.revision}
- component={state.composition.component}
- inputProps={state.composition.props}
- compositionWidth={state.composition.width}
- compositionHeight={state.composition.height}
- fps={state.composition.fps}
- durationInFrames={state.composition.durationInFrames}
+ key={preview.revision}
+ component={preview.composition.component}
+ inputProps={preview.composition.props}
+ compositionWidth={preview.composition.width}
+ compositionHeight={preview.composition.height}
+ fps={preview.composition.fps}
+ durationInFrames={preview.composition.durationInFrames}
controls
loop
acknowledgeRemotionLicense