LoginSignup
6
0

More than 1 year has passed since last update.

Heroku環境でReactアプリのビルドに失敗する(Node version not specified in package.json)原因はNodeのバージョン違いでした

Posted at

内容

Reactアプリのビルドがローカル環境では成功するのにHeroku環境で失敗する事象に出会った。
その原因と解決法についての記事です。
手掛かり→Node version not specified in package.json

開発環境

対象 バージョン
Node.js v15.8.0
npm 7.18.1

概要

React アプリを作成し、Heroku にデプロイした。

当初はビルドに成功していたが、改修を行っていたところビルドに失敗するようになった。
ローカル環境ではビルドに成功しており、Herokuでのみ失敗している。

エラー文は↓

エラー文
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! app-name@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the app-name@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.VWw0a/_logs/2021-06-29T14_37_39_318Z-debug.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed

原因

原因はNodeとnpmのバージョンがpackage.jsonに記述されていないことだった。

エラー文の- Node version not specified in package.jsonに注目すると、「Nodeのバージョンがpackage.jsonで特定されていない」ことがエラーの原因ではないかと推測されている。

package.jsonを見ると確かにNodeのバージョンについての記述がない……。

ローカル環境のNode、npmのバージョンを確認すると以下の通り。

$ node -v
v15.8.0
$ npm -v
7.18.1

Heroku側でのバージョンを確認するためにビルドのログを確認すると以下の通り。

remote:        Resolving node version 14.x...
remote:        Downloading and installing node 14.17.1...
remote:        Using default npm version: 6.14.13

となっており、ビルドに使用するnodeとnpmのバージョンがローカルとHerokuでは違っていることがわかる。
おそらくこれが原因だろうと目星をつけた。

解決

Heroku Node.js Support | Heroku Dev Centerを参考にして、解決のために、package.jsonに以下の記述を追加する。

package.json
{
  ...
  "engines": {
    "node": "15.x",
    "npm": "7.x"
  },
  ...
}

Herokuに変更を反映して再度ビルドを行うと、成功した。

今回の事象では、ローカル環境では正常に動く一方Herokuでは動かない状況だったため、環境の違いが原因ではないかと推測ができた。
ただし最初はビルドに成功していて、改修を行ったタイミングで失敗するようになった原因はわからない。

今回は勉強のための制作だったため被害は出なかったが、これが稼働中のサービスだったり業務で請負ったものだったりと思うと恐ろしいですね。

教訓:環境ごとにバージョンが違うとえらいことになるので、バージョン管理は明確にするべき。

参考文献

Node.js のデプロイのトラブルシューティング | Heroku Dev Center

6
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0