たかぎとねこの忘備録

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

`node-fetch`を使用したときに発生する`Error [ERR_REQUIRE_ESM]: require() of ES Module`の解決方法

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専用パッケージに変換されたため、コンパイルされたJavaScriptrequireを使ってこのパッケージをインポートできなくなったのが原因である。

一番簡単な解決策は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