たかぎとねこの忘備録

プログラミングに関する忘備録を自分用に残しときます。マサカリ怖い。

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に解決策が記載されていた。

stackoverflow.com

端的に言うと、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;

これで解決した。