Reactでbabel-jestのエラーが出て起動できない際の対処法

Reactでbabel-jestのエラー

npx create-react-appからプロジェクトを作成後、yarn startでReactを起動しようとした際に下記のようなbabel-jestのエラーが出て起動できないことがある。

$ yarn start
yarn run v1.22.11
$ react-scripts start

There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.

The react-scripts package provided by Create React App requires a dependency:

  "babel-jest": "^26.6.0"

Don't try to install it manually: your package manager does it automatically.
However, a different version of babel-jest was detected higher up in the tree:

  /Users/node_modules/babel-jest (version: 27.0.5)

Manually installing incompatible versions is known to cause hard-to-debug issues.

If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That will permanently disable this message but you might encounter other issues.

起動できない原因と対処法は英語で表示されるのだが英語が読めない人だと対処するのが難しいのでReact初心者だとここでつまずくケースもある。

エラーの原因

react-scriptsのパッケージのbabel-jestはバージョン26.6.0を推奨しているのだが、それよりも高いバージョンを利用しているとエラーになる。

エラーの対処法

node_module内のbabel-jestのバージョンを26.6.0まで下げるか、.envファイルを作成して現在のバージョンでもエラーにならないようにすればエラーは発生しない。

この記事では対処が簡単な後者の方法について説明する。

まず、ターミナルでtouch .envで.envファイルをプロジェクトフォルダ内に作成する。

touch .env

次に.envを開いて「SKIP_PREFLIGHT_CHECK=true」を貼り付けて保存する。

これでyarn startを実行してもエラーが発生せずReactが起動できるようになる。