使用純 JavaScript(非 TypeScript)
在 Remotion 中選擇退出 TypeScript 並使用純 JavaScript 開發的方法
使用純 JavaScript(非 TypeScript)
自 Remotion 1.3 起,您可以選擇退出 TypeScript 及其型別檢查功能。請注意,放棄 TypeScript 也意味著放棄了它所提供的型別安全優勢,請謹慎評估。
選擇退出 TypeScript
您可以正常導入 .js 和 .jsx 文件。如果您想完全轉移到 JavaScript,請將 index.ts 和 Root.tsx 重新命名,使其帶有 .jsx 副檔名。
重新命名入口文件
# 將 TypeScript 文件重命名為 JavaScript
mv src/index.ts src/index.jsx
mv src/Root.tsx src/Root.jsx更新 Remotion 設定
在 remotion.config.ts(或重新命名後的 remotion.config.js)中,確保入口點指向正確的文件:
// remotion.config.js
const { Config } = require('@remotion/cli/config');
Config.setEntryPoint('./src/index.jsx');更新 package.json 腳本
如果您是從 Remotion 1.2 或更舊版本升級,請考慮修改 npm test 命令,使其也包含 JavaScript 文件,並移除 tsc 命令:
舊版(TypeScript 檢查):
{
"scripts": {
"test": "tsc && jest"
}
}新版(純 JavaScript):
{
"scripts": {
"test": "jest --testPathPattern='\\.(test|spec)\\.(js|jsx)$'"
}
}在 JavaScript 中使用 Remotion API
即使使用 JavaScript,Remotion 的所有 API 仍然可以正常使用:
// src/MyComposition.jsx
import { AbsoluteFill, useCurrentFrame, interpolate } from 'remotion';
export const MyComposition = () => {
const frame = useCurrentFrame();
const opacity = interpolate(frame, [0, 30], [0, 1]);
return (
<AbsoluteFill
style={{
backgroundColor: 'white',
opacity,
}}
>
<h1 style={{ fontSize: 100, textAlign: 'center' }}>
Hello World
</h1>
</AbsoluteFill>
);
};// src/Root.jsx
import { Composition } from 'remotion';
import { MyComposition } from './MyComposition';
export const RemotionRoot = () => {
return (
<>
<Composition
id="MyComposition"
component={MyComposition}
durationInFrames={60}
fps={30}
width={1920}
height={1080}
/>
</>
);
};JSDoc 型別注釋(可選)
即使不使用 TypeScript,您仍然可以使用 JSDoc 注釋獲得部分型別提示:
/**
* @param {{ name: string, duration: number }} props
*/
export const TitleCard = ({ name, duration }) => {
const frame = useCurrentFrame();
// ...
};考量事項
在選擇使用純 JavaScript 之前,請考慮以下優缺點:
使用 JavaScript 的優勢
- 無需學習 TypeScript 語法
- 更快的初始設定(對 TypeScript 不熟悉的開發者)
- 某些舊版程式庫更容易整合
使用 TypeScript 的優勢
- 編譯時捕獲型別錯誤
- 更好的 IDE 自動補全和提示
- Props 型別驗證,減少運行時錯誤
- 更好的程式碼文檔和可維護性
- Remotion 官方提供的所有範例和文檔均使用 TypeScript