Firebase Functionsでnode-fetch
を使用してFirebase Emulatorで動かそうとしたら次のようなエラーが発生した。
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_REQUIRE_ESM]: require() of ES Module /.../node_modules/node-fetch/src/index.js from /.../firebase/functions/lib/routes/tab-one/activities/getActivities.js not supported. Instead change the require of index.js in /...firebase/functions/lib/routes/tab-one/activities/getActivities.js to a dynamic import() which is available in all CommonJS modules.
これはnode-fetch
のバージョン3からESM専用パッケージに変換されたため、コンパイルされたJavaScriptでrequire
を使ってこのパッケージをインポートできなくなったのが原因である。
一番簡単な解決策はCommonJSでビルドされた最後のバージョンであるnode-fetch@2.6.6
をインストールすることである。
このバージョンでは型定義ファイルは自動的に含まれていないので、別途インストールする必要がある。
yarn add node-fetch@2.6.6 yarn add -D @types/node-fetch@2.x
Fix - node-fetch Error [ERR_REQUIRE_ESM]: not supported | bobbyhadz