React NativeでFirebaseを使おうとする際に'While trying to resolve module `idb` from file...'というエラーが出る場合の対処法
Expo CLIを使用して作成したReact NativeプロジェクトでFirebaseを導入してアプリを立ち上げた際に次のようなエラーが発生した。
While trying to resolve module `idb` from file `/プロジェクトのパス/node_modules/@firebase/app/dist/esm/index.esm2017.js`, the package `/プロジェクトのパス/node_modules/idb/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/プロジェクトのパス/node_modules/idb/build/index.cjs`. Indeed, none of these files exist:
StackOverflowに解決策が記載されていた。
端的に言うと、Firebaseのパッケージでは.cjs
という拡張子が使われているが、ExpoやReact Nativeではこの拡張子のファイルがサポートされていないためこのような問題が発生しているらしい。
なので、ルートディレクトリにmetro.config.jsファイルを作成して、手動で.cjs
をパースする設定を追加する必要がある。
// metro.config.js const { getDefaultConfig } = require("@expo/metro-config"); const defaultConfig = getDefaultConfig(__dirname); defaultConfig.resolver.assetExts.push("cjs"); module.exports = defaultConfig;
これで解決した。