Skip to content

🎥 Make videos programmatically with React

input props method

Jonny Burger83552f2f5d9b
diff --git a/packages/bundler/src/index.ts b/packages/bundler/src/index.ts
index 26df5a97b0..f167b77bb4 100644
--- a/packages/bundler/src/index.ts
+++ b/packages/bundler/src/index.ts
@@ -16,6 +16,7 @@ export const startServer = async (
userDefinedComponent: string,
options?: {
webpackOverride?: WebpackOverrideFn;
+ inputProps?: object;
}
): Promise<number> => {
const app = express();
@@ -30,6 +31,7 @@ export const startServer = async (
environment: 'development',
webpackOverride:
options?.webpackOverride ?? Internals.getWebpackOverrideFn(),
+ inputProps: options?.inputProps ?? null,
});
const compiler = webpack(config);
diff --git a/packages/bundler/src/renderEntry.tsx b/packages/bundler/src/renderEntry.tsx
index b6601e3d3f..572f71ad30 100644
--- a/packages/bundler/src/renderEntry.tsx
+++ b/packages/bundler/src/renderEntry.tsx
@@ -7,7 +7,13 @@ import React, {
useState,
} from 'react';
import {render} from 'react-dom';
-import {continueRender, delayRender, Internals, TComposition} from 'remotion';
+import {
+ continueRender,
+ delayRender,
+ getInputProps,
+ Internals,
+ TComposition,
+} from 'remotion';
const Root = Internals.getRoot();
@@ -25,20 +31,12 @@ const Fallback: React.FC = () => {
return null;
};
-const getUserProps = () => {
- const param = new URLSearchParams(window.location.search).get('props');
- if (!param) {
- return {};
- }
- const parsed = JSON.parse(decodeURIComponent(param));
- return parsed;
-};
+const userProps = getInputProps();
const GetVideo = () => {
const video = Internals.useVideo();
const compositions = useContext(Internals.CompositionManager);
const [Component, setComponent] = useState<ComponentType | null>(null);
- const userProps = getUserProps();
useEffect(() => {
if (Internals.getIsEvaluation()) {
@@ -98,8 +96,6 @@ const GetVideo = () => {
);
};
-const userProps = getUserProps();
-
render(
<Internals.RemotionRoot>
<Root {...userProps} />
diff --git a/packages/bundler/src/webpack-cache.ts b/packages/bundler/src/webpack-cache.ts
index 1c6c57f807..c969f85ed5 100644
--- a/packages/bundler/src/webpack-cache.ts
+++ b/packages/bundler/src/webpack-cache.ts
@@ -1,5 +1,6 @@
import fs from 'fs';
import path from 'path';
+import {random} from 'remotion';
type Environment = 'development' | 'production';
@@ -40,20 +41,43 @@ export const getWebpackCacheDir = () => {
}
};
-const remotionCacheLocation = (environment: Environment) => {
- return path.join(getWebpackCacheDir(), getWebpackCacheName(environment));
+const remotionCacheLocation = (
+ environment: Environment,
+ inputProps: object | null
+) => {
+ return path.join(
+ getWebpackCacheDir(),
+ getWebpackCacheName(environment, inputProps)
+ );
};
-export const clearCache = (environment: Environment) => {
- return fs.promises.rmdir(remotionCacheLocation(environment), {
+export const clearCache = (
+ environment: Environment,
+ inputProps: object | null
+) => {
+ return fs.promises.rmdir(remotionCacheLocation(environment, inputProps), {
recursive: true,
});
};
-export const getWebpackCacheName = (environment: Environment) => {
+export const getWebpackCacheName = (
+ environment: Environment,
+ inputProps: object | null
+) => {
+ // In development, let's reset the cache when input props
+ // are changing, because they are injected using Webpack and if changed,
+ // it will get the cached version
+ if (environment === 'development') {
+ return `remotion-${environment}-${random(JSON.stringify(inputProps))}`;
+ }
+ // In production, the cache is independent from input props because
+ // they are passed over URL params. Speed is mostly important in production.
return `remotion-${environment}`;
};
-export const cacheExists = (environment: Environment) => {
- return fs.existsSync(remotionCacheLocation(environment));
+export const cacheExists = (
+ environment: Environment,
+ inputProps: object | null
+) => {
+ return fs.existsSync(remotionCacheLocation(environment, inputProps));
};
diff --git a/packages/bundler/src/webpack-config.ts b/packages/bundler/src/webpack-config.ts
index cccdd60020..d5b3badbb7 100644
--- a/packages/bundler/src/webpack-config.ts
+++ b/packages/bundler/src/webpack-config.ts
@@ -28,6 +28,7 @@ export const webpackConfig = ({
webpackOverride = (f) => f,
onProgressUpdate,
enableCaching = Internals.DEFAULT_WEBPACK_CACHE_ENABLED,
+ inputProps,
}: {
entry: string;
userDefinedComponent: string;
@@ -36,6 +37,7 @@ export const webpackConfig = ({
webpackOverride?: WebpackOverrideFn;
onProgressUpdate?: (f: number) => void;
enableCaching?: boolean;
+ inputProps?: object | null;
}): WebpackConfiguration => {
return webpackOverride({
optimization: {
@@ -52,7 +54,7 @@ export const webpackConfig = ({
cache: enableCaching
? {
type: 'filesystem',
- name: getWebpackCacheName(environment),
+ name: getWebpackCacheName(environment, inputProps ?? null),
}
: false,
devtool: 'cheap-module-source-map',
@@ -73,6 +75,9 @@ export const webpackConfig = ({
new ErrorOverlayPlugin(),
new ReactRefreshPlugin(),
new webpack.HotModuleReplacementPlugin(),
+ new webpack.DefinePlugin({
+ 'process.env.INPUT_PROPS': JSON.stringify(inputProps ?? null),
+ }),
]
: [
new ProgressPlugin((p) => {
diff --git a/packages/cli/src/get-user-props.ts b/packages/cli/src/get-user-props.ts
index 5e1fe3ace2..8bfeee3fe3 100644
--- a/packages/cli/src/get-user-props.ts
+++ b/packages/cli/src/get-user-props.ts
@@ -1,12 +1,12 @@
import {parsedCli} from './parse-command-line';
-export const getUserProps = (): unknown => {
+export const getUserProps = (): object => {
if (!parsedCli.props) {
return {};
}
try {
const parsed = JSON.parse(parsedCli.props);
- return parsed;
+ return parsed as object;
} catch (err) {
console.log(
'You passed --props but it was not valid JSON and could not be parsed.'
diff --git a/packages/cli/src/preview.ts b/packages/cli/src/preview.ts
index 48dea724c9..b7e5f6989a 100644
--- a/packages/cli/src/preview.ts
+++ b/packages/cli/src/preview.ts
@@ -5,18 +5,24 @@ import betterOpn from 'better-opn';
import path from 'path';
import xns from 'xns';
import {getConfigFileName} from './get-config-file-name';
+import {getUserProps} from './get-user-props';
import {loadConfigFile} from './load-config';
+import {parsedCli} from './parse-command-line';
export const previewCommand = xns(async () => {
- const args = process.argv;
- const file = args[3];
+ const file = parsedCli._[1];
const fullPath = path.join(process.cwd(), file);
loadConfigFile(getConfigFileName());
+ const inputProps = getUserProps();
+
const port = await startServer(
path.resolve(__dirname, 'previewEntry.js'),
- fullPath
+ fullPath,
+ {
+ inputProps,
+ }
);
betterOpn(`http://localhost:${port}`);
await new Promise(() => void 0);
diff --git a/packages/cli/src/render.tsx b/packages/cli/src/render.tsx
index ec4336390f..404b9fe39e 100644
--- a/packages/cli/src/render.tsx
+++ b/packages/cli/src/render.tsx
@@ -20,12 +20,11 @@ import {getOutputFilename} from './get-filename';
import {getUserProps} from './get-user-props';
import {getImageFormat} from './image-formats';
import {loadConfigFile} from './load-config';
-import {parseCommandLine} from './parse-command-line';
+import {parseCommandLine, parsedCli} from './parse-command-line';
import {getUserPassedFileExtension} from './user-passed-output-location';
export const render = async () => {
- const args = process.argv;
- const file = args[3];
+ const file = parsedCli._[1];
const fullPath = path.join(process.cwd(), file);
const configFileName = getConfigFileName();
@@ -141,10 +140,10 @@ export const render = async () => {
);
const shouldCache = Internals.getWebpackCaching();
- const cacheExistedBefore = cacheExists('production');
+ const cacheExistedBefore = cacheExists('production', null);
if (cacheExistedBefore && !shouldCache) {
process.stdout.write('🧹 Cache disabled but found. Deleting... ');
- await clearCache('production');
+ await clearCache('production', null);
process.stdout.write('done. \n');
}
bundlingProgress.start(100, 0);
@@ -158,7 +157,7 @@ export const render = async () => {
}
);
bundlingProgress.stop();
- const cacheExistedAfter = cacheExists('production');
+ const cacheExistedAfter = cacheExists('production', null);
if (cacheExistedAfter && !cacheExistedBefore) {
console.log('⚡️ Cached bundle. Subsequent builds will be faster.');
}
diff --git a/packages/core/src/config/input-props.ts b/packages/core/src/config/input-props.ts
new file mode 100644
index 0000000000..a8ad11a538
--- /dev/null
+++ b/packages/core/src/config/input-props.ts
@@ -0,0 +1,11 @@
+export const getInputProps = () => {
+ if (process.env.NODE_ENV === 'production') {
+ const param = new URLSearchParams(window.location.search).get('props');
+ if (!param) {
+ return {};
+ }
+ const parsed = JSON.parse(decodeURIComponent(param));
+ return parsed;
+ }
+ return (process.env.INPUT_PROPS as unknown) as object | null;
+};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a51fcd358c..d5e9f5210a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -4,6 +4,7 @@ export * from './AbsoluteFill';
export * from './audio';
export * from './Composition';
export * from './config';
+export {getInputProps} from './config/input-props';
export * from './easing';
export * from './IFrame';
export * from './Img';
diff --git a/packages/example/src/BetaText/index.tsx b/packages/example/src/BetaText/index.tsx
index 501b060b62..bb66c306ae 100644
--- a/packages/example/src/BetaText/index.tsx
+++ b/packages/example/src/BetaText/index.tsx
@@ -90,7 +90,9 @@ const Row: React.FC<{
);
};
-const BetaText = () => {
+const BetaText: React.FC<{
+ word1: string;
+}> = ({word1}) => {
const videoConfig = useVideoConfig();
const frame = useCurrentFrame();
@@ -138,7 +140,7 @@ const BetaText = () => {
: key === 5
? '5pm'
: key === 3
- ? 'TOMORROW'
+ ? word1 ?? 'TOMORROW'
: key === 1
? 'ANYSTICKER'
: 'BETA'
diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsx
index e8927a5607..c3ffe4db9b 100644
--- a/packages/example/src/Video.tsx
+++ b/packages/example/src/Video.tsx
@@ -1,23 +1,22 @@
import React from 'react';
-import {Composition} from 'remotion';
+import {Composition, getInputProps} from 'remotion';
import {Framer} from './Framer';
import {MissingImg} from './MissingImg';
import {TenFrameTester} from './TenFrameTester';
import {VideoTesting} from './VideoTesting';
-export const Index: React.FC<{[key: string]: unknown}> = ({duration}) => {
+export const Index: React.FC = () => {
+ const inputProps = getInputProps();
return (
<>
- {duration ? (
- <Composition
- id="dinamically-duration"
- component={VideoTesting}
- width={1080}
- height={1080}
- fps={30}
- durationInFrames={duration as number}
- />
- ) : null}
+ <Composition
+ id="dinamically-duration"
+ component={VideoTesting}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={inputProps.duration ?? 20}
+ />
<Composition
id="nested"
lazyComponent={() => import('./NestedSequences')}
@@ -33,6 +32,9 @@ export const Index: React.FC<{[key: string]: unknown}> = ({duration}) => {
height={1080}
fps={30}
durationInFrames={3 * 30}
+ defaultProps={{
+ word1: getInputProps().word1,
+ }}
/>
<Composition
id="black-gradients"