rails s でPlease run rails webpacker:install と表示されて起動しない

Railsの教科書の手順で進めていましたがrails sでアプリが起動しなかったので調べてみました。

結論

node.jsをインストールしてwebpaderをインストールする。

環境

Railsの必要rubyバージョンの確認

下記ページでrails 6.1.6に必要なrubyのバージョンを確認

rails | RubyGems.org | コミュニティのGemホスティングサービス

ruby 2.5.0以降が対応している

状況

rails s でエラー。ログから以下が必要だと読み取れる。

  • rails webpacker:install が必要。
  • RuntimeError が発生している。
/Users/karlley/.rbenv/versions/3.0.3/lib/ruby/3.0.0/digest.rb:6: warning: already initialized constant Digest::REQUIRE_MUTEX
/Users/karlley/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/digest-3.1.0/lib/digest.rb:20: warning: previous definition of REQUIRE_MUTEX was here
=> Booting Puma
=> Rails 6.1.6 application starting in development
=> Run `bin/rails server --help` for more startup options
Exiting
/Users/karlley/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/webpacker-5.4.3/lib/webpacker/configuration.rb:103:in `rescue in load': Webpacker configuration file not found /Users/karlley/Workspace/my_web_apps/helloworld/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /Users/karlley/Workspace/my_web_apps/helloworld/config/webpacker.yml (RuntimeError)

原因

以下の2つがインストールされていないことが原因。

  • webpacker: フロントエンドの開発に必要なアセットを使えるようにするツール
  • node.js: Railsの一部をコンパイルする際に必要なJavaScriptランタイムとして使用する

rails webpacker:install を実行するとnode.jsが必要と表示される。

rails webpacker:install
sh: node: command not found
sh: nodejs: command not found
Node.js not installed. Please download and install Node.js https://nodejs.org/en/download/
Exiting!

対策

  1. webpackerをインストールする為にnode.jsをインストールする。
  2. webpackerをインストールする。

node.jsをhomebrew経由でインストール。

$ brew install node
$ node --version
v18.4.0

再度rails webpacker:install を実行。

$ rails webpacker:install
...
Webpacker successfully installed 🎉 🍰

rails s で正常に起動しました。

$ rails s
=> Booting Puma
=> Rails 6.1.6 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.6.4 (ruby 3.0.3-p157) ("Birdie's Version")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 77606
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop

http://localhost:3000 にアクセスするとwelcome railsが表示されます。

まとめ

やっぱり環境構築は難しい。手順を覚えるのではなく上手く解決できるようにエラーログをしっかり読んで問題を切り分け、対処していくことを心掛けようと思います。

参照

Rails6が立ち上がらない!Node.js, webpacker, yarnのインストール 【開発日記】薬価検索アプリno.5-2 - Qiita