create-react-appが正しくテンプレートを作ってくれなかったときに試みること

何が起こったのか

以下のコマンドを叩いてReactテンプレートを作ろうとした。

$ create-react-app my-app

その結果、my-app配下は以下のようなディレクトリ構成となってしまった。

|-- node_module
|-- package.json
`-- yarn.lock

また、package.jsonの内容も不完全である。
こうなると手も足も出ない。軽率にyarn startしても以下のように突っぱねられる。

$ yarn start
yarn run v1.22.0
error Command "start" not found.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

生成された不完全なpackage.jsonにscriptsの記載が無いためだ。

本当は以下のようなディレクトリ構成となってほしい。

|-- README.md
|-- node_modules
|-- package.json
|-- public
|   |-- favicon.ico
|   |-- index.html
|   |-- logo192.png
|   |-- logo512.png
|   |-- manifest.json
|   `-- robots.txt
|-- src
|   |-- App.css
|   |-- App.js
|   |-- App.test.js
|   |-- index.css
|   |-- index.js
|   |-- logo.svg
|   |-- serviceWorker.js
|   `-- setupTests.js
`-- yarn.lock

解決方法

1. create-react-app のパスを調べる

$ which create-react-app

2. 表示されたパスのバックアップを取る

$ cp /usr/local/bin/create-react-app /usr/local/bin/_create-react-app

3. 表示されたパスを削除する

$ rm -r /usr/local/bin/create-react-app

4. 以下コマンドを実行して再度テンプレートを作り直す

$ npx create-react-app my-app

原因

create-react-appの仕様変更が原因。create-react-appのグローバルインストールがサポートされなくなり、明示的にnpxを使用してプロジェクトを作成するよう仕様変更された。
create-react-app公式ドキュメントに注意書きがある。
create-react-app.dev

If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app to ensure that npx always uses the latest version.

(翻訳)
以前にnpm install -g create-react-appを使用してcreate-react-appをグローバルにインストールしたことがある場合、npxが常に最新バージョンを使用するように、npm uninstall -g create-react-appを使用してパッケージをアンインストールすることをお勧めします。

少なくとも昨年(2019年)12月からこの仕様となったようだ。
github.com