staticFile()
从 v2.5.7 版本开始可用。
将位于 public/ 文件夹中的文件转换为 URL,然后可以将其加载到您的项目中。
tsximport {Img ,staticFile } from "remotion";constmyImage =staticFile (`/my-image.png`);// ...<Img src ={myImage } />;
tsximport {Img ,staticFile } from "remotion";constmyImage =staticFile (`/my-image.png`);// ...<Img src ={myImage } />;
示例
首先在您的视频项目根目录中创建一个 public/ 文件夹:
txtmy-video/├─ node_modules/├─ public/│ ├─ my-image.png│ ├─ font.woff2├─ src/│ ├─ Root.tsx│ ├─ index.ts├─ package.json
txtmy-video/├─ node_modules/├─ public/│ ├─ my-image.png│ ├─ font.woff2├─ src/│ ├─ Root.tsx│ ├─ index.ts├─ package.json
info
public/ 文件夹应始终与包含 remotion 依赖项的 package.json 文件夹位于同一目录中,即使您的 Remotion 代码位于子目录中。
获取您的资产的 URL 引用:
tsximport {staticFile } from "remotion";constmyImage =staticFile (`/my-image.png`); // "/static-32e8nd/my-image.png"constfont =staticFile (`/font.woff2`); // "/static-32e8nd/font.woff2"
tsximport {staticFile } from "remotion";constmyImage =staticFile (`/my-image.png`); // "/static-32e8nd/my-image.png"constfont =staticFile (`/font.woff2`); // "/static-32e8nd/font.woff2"
现在可以通过以下方式加载资产:
<Img />,<Audio/>,<Video/>标签- Fetch API
- FontFace()
- 任何其他支持通过 URL 进行数据获取的加载程序
为什么不能只传递一个字符串?
如果您是 Create React App 或 Next.JS 用户,您可能习惯于只能从字符串中引用资产:<img src="/my-image.png"/>。Remotion 选择使用 staticFile() API 与众不同,因为:
- 在将站点部署到域的子目录时,可以防止出现问题:
https://example.com/my-folder/my-logo.png - 避免与可能共享相同名称的组合名称发生冲突(例如在运行工作室时
http://localhost:3000/conflicting-name) - 允许我们使路径与框架无关,因此您的代码可以在 Remotion、Create React App、Next.JS 和可能其他框架中运行。
获取 public 文件夹中的所有文件
使用 getStaticFiles() API 获取可用选项列表。
处理 URI 不安全字符v4.0.0
自 v4.0 版本起,staticFile() 使用 encodeURIComponent 对文件名进行编码。
如果您到目前为止自己对路径进行了编码,请确保在将路径传递给 staticFile() 之前删除您的编码,以避免双重编码。
在 v4.0 之前,staticFile() 不处理提供的路径中包含的 URI 不安全字符。这可能会导致一些问题,例如当文件名包含字符 #、? 或 & 时。
示例
v4 之前tsxstaticFile("my-image#portrait.png"); //输出: "/my-image#portrait.png"
v4 之前tsxstaticFile("my-image#portrait.png"); //输出: "/my-image#portrait.png"
如果将此 URL 传递给接受 URL 的组件,则 # 后面的部分将被省略,导致无法找到文件而出现错误。
自 v4.0.0 起tsxstaticFile("my-image#portrait.png"); // "/my-image%23portrait.png"
自 v4.0.0 起tsxstaticFile("my-image#portrait.png"); // "/my-image%23portrait.png"
现在图像将被正确加载,但是您必须避免自行对文件名进行编码。