Remotion LabRemotion Lab
Player整合 Player 至 React 應用程式

整合 Player 至 React 應用程式

學習如何將 Remotion Player 整合至 React 應用程式,並在 Remotion Studio 與伺服器端渲染之間共享程式碼。

整合 Player 至 React 應用程式

如果你正在使用 Remotion Player,一個常見的需求是與 Remotion Studio 和/或伺服器端渲染共享程式碼。透過正確的設定,你可以只撰寫一次元件,並將其用於預覽、顯示和渲染。

注意:Remotion 與你的 React 應用程式使用不同的 Webpack 設定。因此,如果你想覆蓋 Webpack 設定,需要同時覆蓋 Remotion 的與 React 應用程式的設定。

使用範本

使用我們的入門範本之一:

這些範本已預設整合了 Player 與 Lambda。

手動設定

使用 React 官方文件中偏好的方式建立 React 專案。常見選擇有:

注意:雖然仍可使用 Create React App,但 React 團隊已不再積極推薦。

建立專案後,安裝必要的 Remotion 相依套件:

# npm
npm i remotion @remotion/cli @remotion/player
 
# pnpm
pnpm i remotion @remotion/cli @remotion/player
 
# yarn
yarn add remotion @remotion/cli @remotion/player

接著,在專案中為 Remotion 建立一個子資料夾,並新增三個檔案:一個 index 檔案、一個用於列出組合的 Root.tsx,以及一個組合檔案。結構如下所示:

 └── src/
+  ├── remotion/
+  │   ├── index.ts
+  │   ├── MyComp.tsx
+  │   └── Root.tsx
   └── app/
       └── App.tsx

組合元件(remotion/MyComp.tsx

你的組合(以範例中的 remotion/MyComp.tsx 為例)可能長這樣:

export const MyComp: React.FC<{ text: string }> = ({ text }) => {
  return <div>Hello {text}!</div>;
};

組合清單(remotion/Root.tsx

你的影片清單(以範例中的 remotion/Root.tsx 為例)可能長這樣:

import { Composition } from 'remotion';
import { MyComp } from './MyComp';
 
export const MyVideo = () => {
  return (
    <>
      <Composition
        component={MyComp}
        durationInFrames={120}
        width={1920}
        height={1080}
        fps={30}
        id="my-comp"
        defaultProps={{ text: 'World' }}
      />
    </>
  );
};

Index 檔案(remotion/index.ts

你的 index 檔案(以範例中的 remotion/index.ts 為例)可能長這樣:

import { registerRoot } from 'remotion';
import { MyVideo } from './Video';
 
registerRoot(MyVideo);

提示:不要將這些陳述式合併至同一個檔案中,否則可能會破壞熱重載(Hot Reloading)。

使用 Remotion Studio

你可以使用 npx remotion studio 指令開啟 Remotion Studio:

npx remotion studio src/remotion/index.ts

注意:在 v4.0 之前,指令為 npx remotion preview

我們建議在 package.json 中新增一個新的腳本以便快速存取:

  "scripts": {
+    "remotion": "remotion studio src/remotion/index.ts"
  }

在應用程式中新增 <Player>

在應用程式中的任意位置,匯入 <Player> 元件與你的組合元件。

import { Player } from '@remotion/player';
import { MyComp } from './remotion/MyComp';
 
export const App: React.FC = () => {
  return (
    <Player
      component={MyComp}
      durationInFrames={120}
      compositionWidth={1920}
      compositionHeight={1080}
      fps={30}
      inputProps={{ text: 'World' }}
    />
  );
};

注意:直接將 React 元件傳遞給 component prop,不要傳遞組合清單。

如果一切正常,你現在可以執行 Web 應用程式並預覽你的影片。

為伺服器端渲染建立打包檔

在任何 Node.js 環境中,你可以呼叫 bundle() 以使用 Webpack 打包影片並進行伺服器端渲染。你需要在 package.json 中新增 @remotion/bundler

server.tsx
import path from 'path';
import { bundle } from '@remotion/bundler';
 
const bundled = await bundle(
  path.join(process.cwd(), 'src', 'remotion', 'index.ts')
);

完整範例請參閱伺服器端渲染

提示:使用 Lambda 時不需要此步驟,你可以使用 CLI 或 deploySite(),它會為你打包影片。

另請參閱