React Native Reanimated 2 エラー「failed to create a worklet」の解決方法
問題の概要
React NativeアプリケーションでReanimated 2を使用する際に、以下のエラーが発生することがあります:
Reanimated 2 failed to create a worklet, maybe you forgot to add Reanimated's babel plugin?
このエラーは、Reanimated 2のワークレット(UIスレッドで実行される関数)の作成に失敗したことを示しています。主な原因はBabelプラグインの設定不足やキャッシュの問題です。
解決方法
1. Babelプラグインの設定
まず、babel.config.js
ファイルにReanimatedのプラグインを正しく追加します:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
// 他のプラグインがある場合...
'react-native-reanimated/plugin', // 必ず最後に追加
],
};
重要
Reanimatedプラグインはプラグイン配列の最後に配置する必要があります。他のプラグインの後に追加してください。
Expoを使用している場合の設定例
module.exports = {
presets: ['babel-preset-expo'],
plugins: [
'react-native-reanimated/plugin',
],
};
2. キャッシュのクリア
設定を変更した後は、必ず開発サーバーのキャッシュをクリアしてください:
npx react-native start --reset-cache
yarn start --reset-cache
expo start -c
# または
expo start --clear
3. 完全なクリーンインストール
上記で解決しない場合、プロジェクトを完全にクリーンに再構築します:
watchman watch-del-all
rm -rf node_modules yarn.lock package-lock.json
npm install
npx react-native start --reset-cache
4. React Navigationを使用している場合
React Navigationと併用する場合は、App.jsファイルの先頭に以下を追加:
import 'react-native-gesture-handler';
5. バージョンの互換性確認
Reanimatedのバージョンが他のライブラリと互換性があるか確認してください:
{
"dependencies": {
"react-native-reanimated": "^3.14.0",
"react-native": "0.74.3",
"react": "18.2.0"
}
}
高度な設定
AndroidでのHermesエンジンの設定
android/app/build.gradle
でHermesを有効にします:
project.ext.react = [
enableHermes: true
]
JSIModuleの設定(React Native CLIのみ)
android/app/src/main/java/com/yourapp/MainApplication.java
に以下を追加:
import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
// ... 他の設定
@Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();
}
};
}
トラブルシューティング
環境別の追加手順
// babel.config.js
module.exports = {
presets: ['babel-preset-expo'],
plugins: ['react-native-reanimated/plugin'],
};
// 実行コマンド
expo start -c
// babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['react-native-reanimated/plugin'],
};
// 実行コマンド
npx react-native start --reset-cache
生産環境でのみエラーが発生する場合
Babel設定が環境別に分かれている場合、開発環境でもプラグインが適用されるようにします:
// 修正前(問題のある設定)
module.exports = {
presets: ["babel-preset-expo"],
env: {
production: {
plugins: ["react-native-reanimated/plugin"],
},
},
};
// 修正後(すべての環境で有効)
module.exports = {
presets: ["babel-preset-expo"],
plugins: ["react-native-reanimated/plugin"],
};
まとめ
Reanimated 2の「failed to create a worklet」エラーは、主に以下の步骤で解決できます:
- Babelプラグインの正しい設定 - プラグイン配列の最後に追加
- キャッシュのクリア - 設定変更後は必ず実行
- 依存関係の更新 - 互換性のあるバージョンを使用
- 完全な再インストール - 問題が解決しない場合
これらの解決策を順に試すことで、ほとんどの場合で問題が解決します。Reanimatedの公式ドキュメントも定期的に確認し、最新のベストプラクティスに従うことをおすすめします。