
Reactで「Can’t import the named export ‘***’ from non EcmaScript module 」エラーがでる時の対応

create-react-appを使ってアプリケーションを作成しているとき、一部の外部ライブラリをimportすると下記のようなエラーが発生しライブラリの読み込みに失敗することがありました。
| 1 2 | ./node_modules/***/*****/****.mjs Can't import the named export '***' from non EcmaScript module (only default export is available) | 
概要
調べてみたところ、create-react-appがwebpack ver.4を使っているため、外部ライブラリに含まれる.mjsファイルをデフォルトでロードしようとして発生しているエラーのようです。
自分の環境では、turf.js をimportしようとすると、index.mjsも同時に読み込んでしまいエラーが発生しました。
厄介なことに、turf.jsに依存している nebula.gl や react-map-gl-draw ライブラリでも同様のエラーが発生します。
回避策
根本的な解決には至りませんが、react-app-rewiredを利用して、create-react-appのwebpack.configを上書きすること対応できました。
- react-app-rewiredをインストール
| 1 | yarn add react-app-rewired | 
- packge.jsonのnpm scriptをreact-app-rewiredを使用するように書き換え
| 1 2 3 4 5 6 |     "scripts": {         "start": "react-app-rewired start",         "build": "react-app-rewired build",         "test": "react-app-rewired test",         "eject": "react-scripts eject"     }, | 
- config-overrides.jsファイルを作成し、webpackConfig.module.rulesをオーバーライドする
| 1 2 3 4 5 6 7 8 9 | module.exports = function override(webpackConfig) {     webpackConfig.module.rules.push({         test: /.mjs$/,         include: /node_modules/,         type: 'javascript/auto'     });     return webpackConfig; }; | 
以上です。