🐟

Next.js で ESM ライブラリを使うための設定(エラー解消:Must use import to load ES Module)

2022/02/14に公開

概略

Next.js で外部 ES Modules ライブラリを使おうとしたときに発生した以下のエラーの解消方法をかきます。
外部 ES Modules を使う際には必要な設定かなと思うので, タイトルもそんな感じにしてます。

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module.
require() of ES modules is not supported.
require() of /xxxx/xxxx/xxxx.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /xxxx/xxxx/package.json.

Error 発生のトリガー

Next.js のプロジェクトにおいて, ES Modules のライブラリを使おうとした場合に起きる。(ES Modules のライブラリを npm install した後, 起動しようとしたら落ちる)

解決策

Next.js の Version を 11.1 以降にし, この上で, next.config.js に以下を書く。

module.exports = {
  // Prefer loading of ES Modules over CommonJS
  experimental: { esmExternals: true },
};

公式での情報は こちら

公式によると, Next.js 12 系では esmExternals のデフォルト設定を true にするという記載があるが, Next.js 12.0.8 段階では同じエラーが出てました。(対応中かな)

ES Modules support includes backward compatibility to support the previous import behavior of CommonJS. In Next.js 12, esmExternals: true will become the default.

Next.js 11.1 より前の Version での対応策

esmExternals の設定が追加される前の対応策は, Issue で書かれている通り, next-transpile-modules を利用して ES Modules のライブラリを読み込むとのことです。

Discussion