staticFile() 相對路徑問題
說明 staticFile() 函式不支援相對路徑、絕對路徑或 public/ 前綴的原因,以及正確的使用方式
staticFile() 相對路徑問題
錯誤訊息
如果您收到以下錯誤:
staticFile() does not support relative paths.
Instead, pass the name of a file that is inside the public/ folder.
這表示您傳遞給 staticFile() 的路徑格式不正確。
常見的錯誤寫法
使用相對路徑(含 ../)
import { staticFile } from "remotion";
// 錯誤:不支援相對路徑
staticFile("../public/image.png");使用 ./ 前綴
import { staticFile } from "remotion";
// 錯誤:不應有 ./ 前綴
staticFile("./image.png");使用絕對路徑
import { staticFile } from "remotion";
// 錯誤:不應使用絕對路徑
staticFile("/Users/bob/remotion-project/public/image.png");包含 public/ 前綴(多餘)
import { staticFile } from "remotion";
// 錯誤:不應包含 public/ 前綴
staticFile("public/image.png");正確的寫法
staticFile() 只接受 public/ 資料夾內檔案的相對名稱,不需要任何路徑前綴:
import { staticFile } from "remotion";
// 正確:直接傳入檔案名稱
staticFile("image.png");若檔案在 public/ 的子資料夾中:
import { staticFile } from "remotion";
// 正確:包含子資料夾路徑,但不含 public/ 前綴
staticFile("assets/images/photo.jpg");
staticFile("fonts/MyFont.woff2");
staticFile("videos/intro.mp4");理解 public/ 資料夾
Remotion 規定靜態資產必須放在專案根目錄的 public/ 資料夾中:
my-remotion-project/
├── public/ ← 所有靜態資產放這裡
│ ├── image.png → staticFile("image.png")
│ ├── audio.mp3 → staticFile("audio.mp3")
│ └── assets/
│ └── logo.svg → staticFile("assets/logo.svg")
├── src/
│ └── MyComp.tsx
└── package.json
staticFile() 函式會自動解析正確的 URL,無論您是在本地開發環境還是在雲端渲染環境中使用。
在元件中使用
以下是在 Remotion 元件中正確使用 staticFile() 的範例:
import { Img, Audio, Video, staticFile } from "remotion";
export const MyComp = () => {
return (
<div>
{/* 圖片 */}
<Img src={staticFile("logo.png")} />
{/* 子資料夾中的圖片 */}
<Img src={staticFile("assets/background.jpg")} />
{/* 影片 */}
<Video src={staticFile("clip.mp4")} />
{/* 音訊 */}
<Audio src={staticFile("music.mp3")} />
</div>
);
};動態資產名稱
staticFile() 同樣支援動態產生的檔案名稱:
import { Img, useCurrentFrame, staticFile } from "remotion";
export const DynamicComp = () => {
const frame = useCurrentFrame();
// 根據幀號選擇不同的圖片
return <Img src={staticFile(`frame-${frame}.png`)} />;
};與 require() 的比較
| 方式 | 動態路徑支援 | Webpack 限制 | 推薦程度 |
|---|---|---|---|
staticFile() | 完整支援 | 無 | 強烈推薦 |
require() | 部分支援 | 有 | 僅在必要時使用 |