[ERR_REQUIRE_ESM]: require() of ES Module not supported の解決方法
問題の概要
Node.js で node-fetch
モジュールを使用する際に、以下のエラーが発生することがあります:
[ERR_REQUIRE_ESM]: require() of ES Module from not supported. Instead change the require of index.js in... to a dynamic import() which is available in all CommonJS modules.
このエラーは、node-fetch
のバージョン 3.0.0 以降が CommonJS の require()
構文をサポートしなくなり、ES Modules (ESM) のみをサポートするようになったために発生します。
原因
Node.js には2種類のモジュールシステムがあります:
- CommonJS:
require()
とmodule.exports
を使用 - ES Modules:
import
とexport
を使用
node-fetch
v3 以降は ES Modules のみをサポートしているため、CommonJS スタイルの require()
でインポートしようとするとエラーが発生します。
解決方法
方法1: ES Modules の使用(推奨)
プロジェクト全体を ES Modules に移行するには、package.json
に以下を追加します:
{
"type": "module"
}
その後、コード内の require()
を import
に変更します:
// CommonJS (従来の方法)
const fetch = require('node-fetch');
// ES Modules (新しい方法)
import fetch from 'node-fetch';
WARNING
注意点:
package.json
に"type": "module"
を追加すると、すべてのモジュールで ES Modules 構文を使用する必要がありますmodule.exports
の代わりにexport
を使用する必要があります- ファイル拡張子を明示する必要がある場合があります(例:
.js
→.mjs
)
方法2: 動的インポートの使用
ES Modules への完全移行が難しい場合は、動的インポートを使用できます:
module.exports = {
name: 'username',
description: "this is the username command",
async execute(message, args) {
// 動的インポートを使用
const fetch = (await import('node-fetch')).default;
// 残りのコード...
}
}
方法3: node-fetch のバージョンダウングレード
一時的な解決策として、node-fetch
のバージョンを 2.x にダウングレードすることもできます:
npm uninstall node-fetch
npm install node-fetch@2.6.6
DANGER
注意:この方法は一時的な解決策です。長期的には ES Modules への移行を推奨します。
方法4: 代替ライブラリの使用
他の HTTP クライアントライブラリを使用する方法もあります:
// axios を使用する場合
const axios = require('axios');
// got を使用する場合
const got = require('got');
コード例
以下は ES Modules を使用した修正後のコード例です:
import fetch from 'node-fetch';
export default {
name: 'username',
description: "this is the username command",
async execute(message, args) {
if (args.length !== 1) {
return message.channel.send("無効なユーザー名です");
}
const ign = args[0];
if (ign.length > 16 || ign.length < 3) {
return message.channel.send("ユーザー名は3〜16文字で指定してください");
}
try {
const uuidResponse = await fetch(`https://api.mojang.com/users/profiles/minecraft/${ign}`);
const uuidData = await uuidResponse.json();
const uuid = uuidData.id;
const onlineInfoResponse = await fetch(`https://api.hypixel.net/status?key=${process.env.HYPIXEL_KEY}&uuid=${uuid}`);
const onlineInfo = await onlineInfoResponse.json();
if (onlineInfo.success && onlineInfo.session.online) {
message.channel.send("オンラインです");
} else {
message.channel.send("オフラインです");
}
} catch (error) {
message.channel.send("エラーが発生しました");
console.error(error);
}
}
}
まとめ
[ERR_REQUIRE_ESM]
エラーは、ES Modules のみをサポートするパッケージを CommonJS 形式でインポートしようとした際に発生します。解決方法は:
- ES Modules への移行(
"type": "module"
の追加とimport
構文の使用) - 動的インポートの使用
- パッケージのバージョンダウングレード
- 代替ライブラリの使用
長期的には ES Modules への移行が推奨されますが、プロジェクトの状況に応じて適切な解決方法を選択してください。